2012-04-23 32 views
3

假設我有一個模型Stock,它有幾個StockPartition(它的屬性名爲partitions,它的一個數組)。如何觀察Ember.Array中的嵌套屬性

Stock模型有一個屬性usedAmount應該改變,當任何的所有partition.amount變化,以及,當然,當加入一個分區/移除被更新。

例子:

stock.get('usedAmount') -> 0 
stock.get('partitions') -> [Class, Class, Class] 
stock.get('partitions')[0].set('amount', 12) 
stock.get('usedAmount') -> I want here to return 12 
stock.get('partitions')[1].set('amount', 12) 
stock.get('usedAmount') -> I want here 24 

怎麼可能Stock觀察每個partitions.amount? 我可以編寫一個函數addPartition,看起來像這樣:

addPartition: function(partition) { 
    partition.addObserver('amount', function() { 
    this.get('owner').notifyPropertyChange('usedAmount'); 
    }); 
} 

但我希望有一個更好的解決方案。

回答

4

我會使用強大的計算屬性。您也可以對Ember.Enumerable的可用的有用的方法使用,請參閱http://jsfiddle.net/pangratz666/BxyY4/

App.partitionsController = Ember.ArrayProxy.create({ 
    content: [], 

    addPartition: function(amount) { 
     this.pushObject(Ember.Object.create({ 
      amount: amount 
     })); 
    }, 

    usedAmount: function() { 
     // reduce by adding all 'amount' values, start with initial value 0 
     return this.reduce(function(previousValue, item) { 
      return previousValue + item.get('amount'); 
     }, 0); 
    }.property('@each.amount') 
}); 

reducedocs被記錄在案。

+0

它的功能就像一個魅力,它的確做得更好! – louiscoquio 2012-04-23 19:11:18

+0

是的,'Ember.Enumerable'爲這些常見任務提供了一些非常好的方法。 – pangratz 2012-04-23 19:31:55