当对象更改时,ArrayController会重新过滤



我遇到了一些问题,使我的数组完全与模板完全同步,ArrayController一直在关注要按下,删除和更新的对象。但是,ArrayController正在过滤结果,当一个对象发生变化并且它的新属性可能最终将其排除在过滤器之外时,它实际上并未被删除。

请参阅下面的代码,为了简化内容的内容,将内容设置为一系列对象,但是在我的应用程序中,它实际上是Ember.A([Ember.Object, Ember.Object])等,依此类推,基础数组是可变的,它一直在与对象一起改变。

App.TabController = Ember.ArrayController.extend({
    content: [
        {id: 1, key: 'unique'},
        {id: 2, key: 'unique'},
        {id: 3, key: 'non-unique'},
    ],
    filteredContent: function() {
        var content = this.get('content');
        return this.filter(function(item, idx, en) {
            return (item.key == 'unique');
        });
    }.observes('content.length').property('content'),
});

上面的代码在将第三个对象排除在模板之外绝对良好,因为它的键与unique的值不匹配。但是,说等于3的对象已更新,并且它是unique的关键更改,它没有将其推入模板 - 我希望它是,我尝试了一些解决方案,但无济于事。

我还会注意,如果任何新对象都带有正确的键当对象更改时,我知道ArrayController正在做它的工作,它只是不重新过滤结果。

这甚至可以在不强制重新渲染或其他一些巫术的情况下进行?

我会使用过滤器计算的属性宏,有点像这样:

App.TabController = Ember.ArrayController.extend({
  filteredContent: Ember.computed.filterBy('content', 'key', 'unique')
});

用于避免重新计算数组并提高性能,使用 ember.ArrayComputed 。这是与您的情况一起使用的方法:

App.TabController = Ember.ArrayController.extend({
  filteredContent: Ember.arrayComputed("content.[]", {
    initialValue: [],
    addedItem: function(accum, item) {
      if (item.key == 'unique') {
        accum.pushObject(item);
      }
      return accum;
    },
    removedItem: function(accum, item) {
      accum.removeObject(item);
      return accum;
    }
  })
});

最新更新