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

这一生的挚爱 提交于 2020-01-07 05:28:05

问题


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.

Template

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

Component

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

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.

What am I missing?


回答1:


Your computed property is listening for changes to the array itself. Try listening for changes to the arrays items with 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}`;
  });
}),

UPDATE

Here is a twiddle showing that the above solution fixes the problem.

If it's not working on your end then there is some issue with what your api is returning.

As per my comments about how to send actions. You are using 2 year old syntax from Ember 1.13 which I am not familiar with.

I suggest you read the docs for the version you are running Ember 2.15




回答2:


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

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

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'.



来源:https://stackoverflow.com/questions/46211089/emberjs-refreshing-a-data-model-does-not-update-associated-computed-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!