EmberJS:刷新数据模型不会更新关联的计算属性 [英] EmberJS: refreshing a data model does not update associated computed properties

查看:70
本文介绍了EmberJS:刷新数据模型不会更新关联的计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一条路由可以根据用户请求更新其数据(假设后端为同一调用返回不同的数据,也许是股票数据,或者只是随机数).

Let's say there is a route with capabilities to update it's data when requested by the user (assume the backend returns different data for the same call, maybe it's stock data, or just random numbers).

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

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

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

Now, a component consuming this model directly will update its view as expected.

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

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

But, if the component is using a computed property observing the model, then the updates do not carry through.

模板

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

For a full repro, you can check out: https://github.com/myartsev/ember-computed-properties-on-data-model

最新提交是非工作的计算属性案例.
上一次提交是当一切仍然静止时直接使用模型时可以正常工作.

The latest commit is the non-working computed properties case.
The previous commit is when everything is still working correctly when using the model directly.

我想念什么?

推荐答案

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

关闭循环;@Subtletree的答案非常接近,这让我思考正确的方向.

To close the loop; the answer from @Subtletree was very close and it got me thinking on the right track.

差异很小但很重要, model.[] 仅在返回的数据大小更改时起作用;元素已添加或删除.就我而言,返回的数据大小保持不变,只是其值得到更新.因此正确的方法是侦听您要查找的依赖项,在这种情况下为"model.@ each.bar".

The difference was subtle but important enough, model.[] will only work if the size of the data being returned changes; elements are added or removed. In my case, the size of the data returned remained constant, only it's value got updated. So the correct way was to listen to the dependent key you are looking for, in this case, 'model.@each.bar'.

这篇关于EmberJS:刷新数据模型不会更新关联的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆