2012-02-21 50 views
1

我有一個包含「事物」數組的控制器。在每一件事情中,都有一系列「亞樹」。我想創建一個計算屬性,其中包含所有東西的所有子項(扁平數組的子項)。使用@each可以觀察數組中的數組嗎?

我的計算屬性取決於[email protected]。我發現,如果我設置subthings屬性的東西,我的計算屬性更新。但是,如果我呼叫pushObjects向我的現有的subthings數組添加新數據,我的計算屬性不會更新。

我創建了一個jsfiddle來演示。代碼如下:

App = Em.Application.create({}); 

App.controller = Em.Object.create({ 
    things: [ 
     Em.Object.create({subthings:[]}), 
     Em.Object.create({subthings:[]}), 
     Em.Object.create({subthings:[]})   
    ], 

    allSubThings : function() { 
     var things = this.get('things'); 
     var results = []; 
     things.forEach(function(thing) { 
      results.pushObjects(thing.get('subthings')); 
     }); 
     return results; 
    }.property('[email protected]').cacheable()   
}); 


setTimeout(function() { 
    var things = App.controller.get('things'); 
    // This works: 
    things.objectAt(0).set('subthings',[1,2,3]); 
}, 1000); 

setTimeout(function() { 
    var things = App.controller.get('things'); 
    // This does not: 
    things.objectAt(1).get('subthings').pushObjects([1,2,3]); 
}, 2000); 

謝謝!

回答

2

添加另一個@each的屬性列表.property('[email protected]@each.length')

http://jsfiddle.net/tomwhatmore/pDQeT/3/

+0

行之有效,謝謝!也許我不太明白@each在這裏做什麼。看來你的解決方案是觀察「子集」數組中每個元素的長度屬性,而不是子集數組本身的長度。 – rharper 2012-02-21 16:41:59

+3

來自Ember文檔:http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/「請注意@each只能深入一層,不能使用像todos這樣的嵌套表單。 .owner.name或todos。@ each.owner。@ each.name – 2014-03-18 19:54:55