EmberJS根据数组计算属性不起作用

时间:2016-07-07 19:13:07

标签: javascript arrays ember.js computed-properties

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

3 个答案:

答案 0 :(得分:3)

使用pushObjectthis.get('selectedRequirements').pushObject(obj);

答案 1 :(得分:1)

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

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计算属性

答案 2 :(得分:0)

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