如何解决Ember.JS强制重新计算属性
所以我的Ember应用程序中有一个计算属性。声明为myComProp: computed('itemTrait',function () {...})
。 myComProp属于项目模型。在一个单独的组件(listItem)中,我有一个属性,它是myComProp的别名:myAlias: alias('itemModel.myComProp')
。现在listItems是listItems数组的成员,其属性在Web应用程序中呈现。
现在该属性为别名,是否有办法强制计算的属性重新计算?
我曾尝试将别名设置为跟踪属性,但这样做会将调用堆栈作为字符串而不是计算函数的实际结果返回。
更新
添加此内容可以更好地进行解释。
// itemModel.js
export default parentModel.extend({
//irrelevant properties
myComProp: computed('itemTrait',function() {
// logic
})
});
在其他地方有两个组成部分。一个是页面的一部分,呈现了itemModels的列表,另一部分是itemModel的表示(由list组件从数据存储中获取)
// itemModelRep/component.js
export default Component.extend({
// other properties
myAlias('item.myComProp')
// itemModel is represented in the list by 'item'
});
列表:
//itemList.js
export default parentDisplay.extend({
// other properties
get items() {
// this is what is used as the list items
// it basically gets a list of items from the itemModel record set in
// the data store
listOfItems.forEach((item) => {
// Other stuff going on
// Here I want to force the property to recompute
};
}
});
基本上,myComProp获得相关日期,并且当我用新项目更新列表时,我想重新计算相关日期。 get事件基于跟踪列表,因此每次将实时供稿添加到该事件时便会运行
解决方法
让我看看我是否理解您的问题:
// app/models/item.js
myComProp: computed('itemTrait',function () {...});
和
// app/components/list-item.js
itemModel: null,// passed in
myAlias: alias('itemModel.myComProp'),listItems: null,init() {
this._super(...arguments);
this.listItems = [this.itemModel];
}
actions: {
changeItem() {
this.itemModel.itemTrait = 'new value';
}
}
在调用changeItem
时,itemModel.itemTrait
发生了变化,而listItems
没有表达这些变化吗?
如果是,则问题不在于您的计算属性或别名未更新。问题在于该列表不知道需要更新。
快速修复:
actions: {
changeItem() {
this.itemModel.itemTrait = 'new value';
this.notifyPropertyChange('listItems');
}
}
以下是有关notifyPropertyChange
的一些信息:https://api.emberjs.com/ember/3.20/classes/Component/methods/notifyPropertyChange?anchor=notifyPropertyChange
如果我误解了您的问题,请解释和/或更新您的问题。
此答案自Ember 3.20起有效
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。