0

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

这是小提琴: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'));
    }
});
4

1 回答 1

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. 计算属性现在观察 colorsHolder 对象并专门观察它们的“颜色”属性
  3. 我已经使用 filterProperty 来确定是否有任何对象具有颜色值 === 'blue'
于 2013-04-04T02:08:25.077 回答