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

fgu*_*len 5 ember.js computed-properties

我有一个像这样的对象:

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

export default Ember.Service.extend({
  counters: Ember.Object.create()
})
Run Code Online (Sandbox Code Playgroud)

myService.counters是一个散列,如:

{
  clocks: 3,
  diamons: 2
}
Run Code Online (Sandbox Code Playgroud)

我想为这个对象添加一个计算属性,返回myService.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);
})
...
Run Code Online (Sandbox Code Playgroud)

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

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() {})`.
Run Code Online (Sandbox Code Playgroud)

但如果我提出改变建议:

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

计数属性不被更新.

我能使它工作的唯一方法是这样的:

// 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);
})
...
Run Code Online (Sandbox Code Playgroud)

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

loc*_*cks 4

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

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

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

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