我有一个 EmberJS 控制器,它具有以下计算属性:
hasSelectedRequirements: Ember.computed('selectedRequirements.[]', function() {
console.log("this should get printed but it doesn't");
return this.get('selectedRequirements').length > 0;
}),
它设置了我在模板中使用的布尔标志,以有条件地显示 html。
我还有一个按钮,单击该按钮时,将获取表单数据并通过调用 addRequirement 操作将元素推送到 selectedRequirements 数组中
actions: {
addRequirement() {
...
// extract data from form and create the requirement variable
var selectedRequirements = this.get('selectedRequirements');
selectedRequirements.push(requirement);
this.set('selectedRequirements', selectedRequirements);
console.log(this.get('selectedRequirements')); // does print as expected
}
}
如果我将 addRequirement 函数更改为此,则 hasSelectedRequirements 计算属性的函数处理程序将按预期运行,并且 console.log 语句有效:
actions: {
addRequirement() {
...
// extract data from form and create the requirement variable
var selectedRequirements = this.get('selectedRequirements');
selectedRequirements.push(requirement);
// create a new, local array
var arr = new Array();
arr.push(1);
this.set('selectedRequirements', arr);
console.log(this.get('selectedRequirements')); // does print as expected
}
}
似乎 Ember 的计算属性依赖于观察到的数组是一个完全不同的数组?
问题是计算属性无法识别元素已添加到 selectedRequirements 数组中,并且计算属性函数永远不会被调用(console.log 语句永远不会运行)。为什么计算属性无法识别 selectedRequirements 数组已被修改,如何修复计算属性代码?