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

EmberJS, how to observe changes in any object of a hash

我有一个像这样的对象:

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

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

myService.counters 是一个 散列 ,例如:

{
  clocks: 3,
  diamons: 2
}

我想向该对象添加一个计算属性,例如returnsmyService.counters.clocks加上myService.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);
})
...

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

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

您不能使用通配符,因为它会严重降低性能。多个属性有一个 shorthand:

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

我还更新了计算逻辑以使用 Array#reduce 和带有隐式 return 的箭头函数。