Reputation: 10726
Suppose I have a model Stock
that has several StockPartition
(its a property called partitions
, its an Array).
The Stock
model has a property usedAmount
that should change when any of all partition.amount
changes, and, of course, be updated when a partition is added/removed.
Example :
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
How could Stock
observes each partitions.amount
?
I can write a function addPartition
that looks like this :
addPartition: function(partition) {
partition.addObserver('amount', function() {
this.get('owner').notifyPropertyChange('usedAmount');
});
}
But I hope there is a better solution.
Upvotes: 3
Views: 1533
Reputation: 16163
I would make usage of the powerful computed properties. Also you can make usage of the helpful methods available on Ember.Enumerable
's, see 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')
});
The reduce
is documented in the docs.
Upvotes: 4