2017-09-14 62 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