控制器看不到更新的模型——异步处理



我有一个非常简单的要求,但就像Ember.JS中的许多事情一样,我正在努力实现它。

我有一个概述屏幕,其中几条记录显示在一个表中。

要呈现概述屏幕,我使用以下Route

App.LocationsIndexRoute = Ember.Route.extend({
  setupController: function(controller) {
    var locations = App.Location.find();
    controller.set('content', locations);
  },
  renderTemplate: function() {
    this.render('locations.index',{into:'application'});
  }
});

工作正常。现在我想有条件地渲染overviewtable。

  • 如果有记录,则呈现表。
  • 如果没有记录,显示一条消息。

我尝试使用下面的控制器来实现这个。

App.LocationsIndexController = Ember.ArrayController.extend({
  locationsPresent: function() {
    var model = this.get('content');
    return model.content.length > 0;
  }.property()
});

和下面的模板

{{#if locationsPresent}}
  <table class="table table-hover">
  <tr>
    <th>Latitude</th>
    <th>Longitude</th>
    <th>Accuracy</th>
    <th></th>
    <th></th>
  </tr>
    {{#each location in model}}
      <tr>
      <td>{{location.latitude}}</td>
      <td>{{location.longitude}}</td>
      <td>{{location.accuracy}}</td>
      <td>{{#linkTo locations.edit location}}Edit{{/linkTo}}</td>
      <td><button {{action removeItem location}}>Delete</button></td>
      </tr>
    {{/each}}
  </table>
{{else}}
  No locations present.
{{/if}}

计算的locationsPresent属性在页面呈现之前被调用一次。此时,我假设模型仍被加载为长度= 0。

当页面呈现时,App.Locations.find()中的位置是可用的,但是locationpresent不再被调用,这意味着页面决定呈现No locations present.消息。

我浏览了Ember页面中的管理异步,并假设如果底层模型发生变化(如果它完全加载),计算机属性locationsPresent将被更新,如页面所述:

为author使用computed属性消除了在底层属性更改时在回调中显式调用计算的需要。

我很想知道我做错了什么,我怎么能解决这个问题,但更重要的是,为什么我似乎错过了烬. js的一些核心概念。如果有人能告诉我在文档/指南中有什么正确的解释,我很想知道。

我认为这是一个很容易解决的问题。您需要添加正在观察的属性。像这样:

locationsPresent: function() {
  var length = this.get('content.length');
  return length > 0;
}.property('content.@each')
如果locationpresent需要在添加内容时重新计算,

添加@each是必要的。我认为你也可以观察" content。isloaded "

最新更新