gpt4 book ai didi

javascript - EmberJS - 将相同的值分配给依赖属性时更新计算属性

转载 作者:行者123 更新时间:2023-11-30 17:59:11 24 4
gpt4 key购买 nike

在我的 ember 应用程序中,有一个模型的属性可能会或可能不会更改的事件。我的 Controller 中还有一个计算属性,它依赖于我的模型属性和应用程序中的另一个变量(不属于模型)。

即使事件触发时模型的属性没有改变,其他应用程序变量也会改变,这会影响 Controller 的计算属性,我希望这些改变反射(reflect)在事件触发上。

我注意到,如果为属性分配了相同的值,ember 将不会“更新”该属性,而且我似乎找不到强制更新的方法。

现在我有一个奶酪修复,如果模型的属性没有改变,我将值更改为其他值,然后将其重置回原来的值以触发 Controller 的计算属性。这不是很有效或干净。有没有其他方法来处理这个问题?

编辑:简要说明我在做什么......

session.other_application_var = [1, 2];

App.MyModel = Ember.Object.extend({
model_prop: 1
});

//an instance of MyModel is assigned to the index route's model

App.IndexController = Ember.ObjectController.extend({
comp_prop: function(){
var sum = this.get('model.model_prop');
session.other_application_var.forEach(function(num){
sum += num;
});
return sum;
}.property('model.model_prop)
});

所以基本上,如果我更改 session.other_application_var,例如添加另一个元素,我希望 comp_prop 更新。

最佳答案

您可以使用特殊的 @each property观察数组的变化。以下更改意味着 comp_prop 将在 model.model_prop 或 'App.otherStuff.@each' 更改时更新。

App = Ember.Application.create({
otherStuff: [2,3,4]
});

App.IndexController = Ember.ObjectController.extend({
comp_prop: function(){
var sum = this.get('model.model_prop');
var otherStuff = App.get('otherStuff');
otherStuff.forEach(function(num){
sum += num;
});
return sum;
}.property('model.model_prop', 'App.otherStuff.@each')
}

Full working example JSBin

关于javascript - EmberJS - 将相同的值分配给依赖属性时更新计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17456427/

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