Ember对象上的计算属性不起作用

时间:2014-03-11 20:43:14

标签: ember.js

我有一个Ember对象如下:

App.Basket = Ember.Object.extend({

    items: [],

    numItems: function () {
        return this.items.length;
    }.property('items'),

    addItem: function (item) {
        this.items.push(item);
        window.console.log(this.items.length, this.get('items').length, this.numItems);
    }

});

App.userBasket = App.Basket.create({
    items: [{name: 'testing'}]
});

它在模板中绑定:

{{App.userBasket.numItems}}

通过在create上填充items数组来正确显示初始值。

但是,我有一个调用App.userBasket.addItem({name: 'testing2'});的按钮。

在控制台中,返回正确的计数。但是,视图不会更新。这是为什么?

1 个答案:

答案 0 :(得分:4)

您需要将items.[]添加到计算属性依赖项中。否则它只会观察像basket.set('items', someItems)这样的数组赋值的变化,你还想观察数组本身的变化:

numItems: function () {
    return this.items.length;
}.property('items', 'items.[]'),

items.push是来自Array的原生方法,ember添加一个名为pushObject的方法,其行为与push相同,但会通知观察者。这需要numItems了解items属性

的变化
addItem: function (item) {
    this.items.pushObject(item);
    window.console.log(this.items.length, this.get('items').length, this.numItems);
}
相关问题