gpt4 book ai didi

javascript - 如何在 Ember.js 中创建一个计算属性来查看单个 Ember 数据属性是否脏?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:38 25 4
gpt4 key购买 nike

我试过在 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() 之后,即使 name 不再出现在 changedAttributes() 中,该属性也不会重新计算为 false 。我怎样才能使这个计算属性起作用?

这是一个简化的测试用例:https://ember-twiddle.com/87b1af7abfb103554cb2?openFiles=models.author.js%2C

最佳答案

我认为这是由于 hasDirtyAttributes 没有在任何地方使用,这意味着更改观察器不会正确设置。

一个简单的修复是:

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

这确保 hasDirtyAttributes 属性被使用,并且当其他属性更改时该属性将被更新。一般来说,如果您有一个属性作为依赖键,您绝对应该在计算函数体中获取它,如果您在计算函数体中获取一个属性函数体,它应该始终被列为依赖键。我相信它以这种方式工作的原因是由于性能优化。

关于javascript - 如何在 Ember.js 中创建一个计算属性来查看单个 Ember 数据属性是否脏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36186068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com