0

我有一个 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 数组已被修改,如何修复计算属性代码?

4

3 回答 3

3

使用pushObject喜欢this.get('selectedRequirements').pushObject(obj);

于 2016-07-07T19:56:41.560 回答
1

似乎 Ember 的计算属性(至少使用 array.[] 语法观察)需要一个新数组才能识别更改。因此,我找到的最佳解决方案是使用切片创建数组的副本:

actions: {
    addRequirement() {
        ...
        // extract data from form and create the requirement variable

        var selectedRequirements = this.get('selectedRequirements');
        selectedRequirements.push(requirement);
        this.set('selectedRequirements', selectedRequirements.slice(0));

        console.log(this.get('selectedRequirements')); // does print as expected
    }
}

这保证了每次调用 addRequirement 操作时都正确设置了 hasSelectedRequirements 计算属性

于 2016-07-07T20:00:09.860 回答
0

使用pushObject代替pushremoveObject代替splice将触发该computed属性。

于 2020-12-14T10:33:01.217 回答