我有一个像这样的对象:
// 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.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);
})
...
如何在这种情况下使用任何种类的通配符?
答案 0 :(得分:3)
@each
和[]
用于观察数组元素和数组。
您无法使用通配符,因为它会成为一个严重的性能接收器。有多个属性的简写:
count: Ember.computed('counters.{clocks,diamons}', function() {
return this.get('counters').reduce((memo, num) => memo + num, 0);
})
我还更新了使用Array#reduce
的计算逻辑和隐式返回的箭头函数。