Ker*_*ick 3 javascript ember.js ember-data computed-properties
我试过在Ember Data 1.13.16模型上创建一个计算属性,如下所示:
export default DS.Model.extend({
name: DS.attr('string'),
isNameDirty: Ember.computed('name', 'hasDirtyAttributes', function() {
return !!this.changedAttributes()['name'];
})
});
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,在调用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'];
})
Run Code Online (Sandbox Code Playgroud)
这可确保hasDirtyAttributes消耗属性,并在其他属性更改时更新此属性.一般来说,如果你有一个属性作为一个依赖键,你肯定应该get在计算函数体中,并且如果你get在函数体中定义一个属性,它应该总是被列为一个依赖键.我相信它以这种方式工作的原因是由于性能优化.