簡體   English   中英

如何在Ember.js中創建計算屬性以查看單個Ember Data屬性是否為臟?

[英]How do you create a computed property in Ember.js to see if a single Ember Data attribute is dirty?

我試過在Ember Data 1.13.16模型上創建一個計算屬性,如下所示:

export default DS.Model.extend({
  name: DS.attr('string'),
  isNameDirty: Ember.computed('name', 'hasDirtyAttributes', function() {
    return !!this.changedAttributes()['name'];
  })
});

但由於某些原因,打完電話后model.save()的財產永遠不會重新計算為false,即使name不再出現在changedAttributes() 如何使此計算屬性有效?

這是一個簡化的測試用例: https//ember-twiddle.com/87b1af7abfb103554cb2?openFiles = model.author.js%2C

我相信這是由於hasDirtyAttributes沒有被消耗在任何地方,這意味着更改觀察者將無法正確設置。

一個簡單的修復是:

isNameDirty: Ember.computed('name', 'hasDirtyAttributes', function() {
  if (!this.get('hasDirtyAttributes')) { return false; }
  return !!this.changedAttributes()['name'];
})

這可確保消耗hasDirtyAttributes屬性,並在其他屬性更改時更新此屬性。 一般來說,如果你有一個屬性作為依賴鍵,你肯定應該在計算函數體中get它,如果你在函數體中get一個屬性,它應該總是被列為一個依賴鍵。 我相信它以這種方式工作的原因是由於性能優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM