2017-09-14 77 views
0

假设有一条路径具有在用户请求时更新其数据的功能(假设后端为同一个调用返回不同的数据,也许是股票数据,或者只是随机数)。EmberJS:刷新数据模型并不会更新关联的计算属性

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是当直接使用模型时,所有内容仍然正常工作时。

我错过了什么?

回答

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

要关闭循环; @Subtletree的回答非常接近,这让我想到了正确的道路。

区别很微妙但足够重要,model.[]只有在返回的数据大小发生变化时才会起作用;元素被添加或删除。在我的情况下,返回的数据的大小保持不变,只是它的值得到更新。所以正确的方法是听你正在寻找的依赖键,在这种情况下,'model。@ each.bar'。

2

您的计算属性正在侦听对阵列本身的更改。尝试用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示出的是,上述的解决方案解决了这个问题监听改变阵列的项目。

如果它不在你的最后,那么你的api返回时会有一些问题。

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

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

+0

如果你还没有,你也应该加入余烬。 https://ember-community-slackin.herokuapp.com/:) – Subtletree

+0

你试过这个吗?它不工作:(烬数据模型是一个类,而不是一个数组,至少不是直接的(它确实有类内的数组) – myartsev

+0

你没有正确地发送行动到组件,你只是发送一个字符串,尝试'{{foo-component model = model invalidateModel =(action“invalidateModel”)}}' – Subtletree