How Nested Properties Are Observed in Ember.Array

Suppose I have a model Stockthat has several StockPartition(its property is called partitions, its Array).

The model Stockhas a property usedAmountthat should change when any of them changes partition.amountand, of course, will be updated when a section 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 Stockcan everyone observe partitions.amount? I can write a function addPartitionthat looks like this:

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

But I hope there is a better solution.

+3
source share
1 answer

. , 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')
});

reduce docs.

+4

All Articles