EmberJS:刷新数据模型不会更新关联的计算属性

EmberJS: refreshing a data model does not update associated computed properties

假设有一条路由能够在用户请求时更新其数据(假设后端 returns 同一调用的不同数据,可能是股票数据,或者只是随机数)。

export default Ember.Route.extend({
  model() {
    return this.get('store').findAll('foo');
  },

  actions: {
    invalidateModel() {
      this.refresh();
    }
  }
});

现在,直接使用此模型的组件将按预期更新其视图。

Model: {{#each model as |m|}}{{m.bar}}{{/each}}
<button {{action "refreshModel"}}>Refresh model</button>

但是,如果组件使用计算 属性 观察模型,则更新不会进行。

模板

Model: {{#each computedModel as |m|}}{{m}}{{/each}}
<br>
<button {{action "refreshModel"}}>Refresh model</button>

组件

computedModel: Ember.computed('model', function() {
  return this.get('model').map(function(m) {
    return `Computed: ${m.data.bar}`;
  });
}),

如需完整重现,您可以查看:https://github.com/myartsev/ember-computed-properties-on-data-model

最新的提交是非工作计算属性案例。
previous commit 是直接使用模型时一切仍然正常工作的时候。

我错过了什么?

您的计算 属性 正在侦听对数组本身的更改。尝试使用 model.[]

监听数组项的变化

https://guides.emberjs.com/v2.15.0/object-model/computed-properties-and-aggregate-data/#toc_code-code-vs-code-each-code

computedModel: Ember.computed('model.[]', function() {
  return this.get('model').map(function(m) {
    return `Computed: ${m.data.bar}`;
  });
}),

更新

Here is a twiddle 显示上述解决方案解决了问题。

如果它在您这边不起作用,那么您的 api 返回的内容存在一些问题。

根据我对如何发送操作的评论。您使用的是我不熟悉的 2 岁 syntax from Ember 1.13

我建议你阅读the docs for the version you are running Ember 2.15

computedModel: Ember.computed('model.@each.bar', function() {
  return this.get('model').map(function(m) {
    return `Computed: ${m.data.bar}`
  });
})

关闭循环; @Subtletree 的回答非常接近,这让我的思考走上了正确的轨道。

差异很细微但很重要,model.[] 仅在返回数据的大小发生变化时才有效;添加或删除元素。在我的例子中,返回数据的大小保持不变,只是更新了它的值。所以正确的方法是听你正在寻找的依赖键,在这种情况下,'model.@each.bar'.