为什么这个余烬没有为@each计算属性?

时间:2013-04-04 01:42:05

标签: ember.js

我正在尝试使用一个计算属性来观察数组中每个元素的特定属性的更改。这是小提琴。单击更改按钮,计算属性不会触发。为什么呢?

这里是小提琴: http://jsfiddle.net/inconduit/PkT8x/145/

这是相关代码

App.color1 = Ember.Object.create({ color : "red"});

// a contrived object that holds an array of color objects
App.colorsHolder = Ember.Object.create({
    colors : Ember.A([App.color1]),
});

App.ApplicationController = Ember.Controller.extend({
    colorsHolder : App.colorsHolder,

    // this should fire when you click the change button, but it does not
    colorsContainBlue : function() {
        console.log("fired colorsContainBlue");
        this.colorsHolder.colors.forEach(function(colorObj) {
            if(colorObj.get('color') == 'blue')
                return true;
        });
        return false;
    }.property('colorsHolder.@each.color'),                                  

    // this is a function called by an action in the template
    changeToBlue: function() {
        App.color1.set('color','blue');
        console.log("changed the color to: " + App.color1.get('color'));
    }
});

1 个答案:

答案 0 :(得分:2)

这个小提琴是一个基于你提供的例子。

http://jsfiddle.net/skane/PkT8x/147/

colorsContainBlue : function() {
    console.log("fired colorsContainBlue");
    if (this.colorsHolder.filterProperty('color', 'blue').length !== 0) {
        return true;
    }
    return false;
}.property('colorsHolder.@each.color'),                                  

changeToBlue: function() {
    this.get('colorsHolder').objectAt(0).set('color','blue');
}

我在你的例子中改变了很多东西,包括:

  1. changeToBlue现在更改ApplicationController的colorHolder对象中的属性(重要)
  2. computed属性现在可以观察colorsHolder对象,并专门观察它们的“颜色”道具
  3. 我使用了filterProperty来确定任何对象是否有颜色值==='blue'
相关问题