【问题标题】:why isn't this ember computed property firing for @each?为什么这个 ember 计算属性不为 @each 触发?
【发布时间】:2013-04-04 01:42:04
【问题描述】:

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

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

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    这个小提琴是基于你提供的一个工作示例。

    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 对象并专门观察它们的“color”属性
    3. 我已使用 filterProperty 来确定是否有任何对象具有颜色值 === 'blue'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2019-07-09
      • 2018-07-29
      • 2018-08-24
      • 2019-03-02
      相关资源
      最近更新 更多