EmberJS,如何观察散列中任何对象的变化

时间:2016-03-07 11:35:22

标签: ember.js computed-properties

我有一个像这样的对象:

// app/services/my-service.js
import Ember from 'ember';

export default Ember.Service.extend({
  counters: Ember.Object.create()
})

myService.counters哈希,如:

{
  clocks: 3,
  diamons: 2
}

我想在此对象中添加计算属性,返回myService.counters.clocksmyService.counters.diamons的总和

// app/services/my-service.js
...
count: Ember.computed('counters.@each', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

但是不接受观察者配置,我有错误:

Uncaught Error: Assertion Failed: Depending on arrays using a dependent key ending with `@each` is no longer supported. Please refactor from `Ember.computed('counters.@each', function() {});` to `Ember.computed('counters.[]', function() {})`.

但是,如果我提出改变建议:

// app/services/my-service.js
...
count: Ember.computed('counters.[]', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

count 属性未更新。

我能让它发挥作用的唯一方法就是:

// app/services/my-service.js
...
count: Ember.computed('counters.clocks', 'counters.diamons', function(){
  return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...

如何在这种情况下使用任何种类的通配符?

1 个答案:

答案 0 :(得分:3)

@each[]用于观察数组元素和数组。

您无法使用通配符,因为它会成为一个严重的性能接收器。有多个属性的简写:

count: Ember.computed('counters.{clocks,diamons}', function() {
    return this.get('counters').reduce((memo, num) => memo + num, 0);
})

我还更新了使用Array#reduce的计算逻辑和隐式返回的箭头函数。