【问题标题】:How observes nested properties in Ember.Array如何观察 Ember.Array 中的嵌套属性
【发布时间】:2012-04-23 17:50:17
【问题描述】:

假设我有一个模型Stock,它有几个StockPartition(它的一个属性叫做partitions,它是一个数组)。

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

但我希望有更好的解决方案。

【问题讨论】:

    标签: arrays ember.js observable


    【解决方案1】:

    我会使用强大的计算属性。您还可以使用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 中。

    【讨论】:

    • 是的,Ember.Enumerable 为这类常见任务提供了一些非常好的方法。
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2017-05-22
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多