I have an Object like:
// app/services/my-service.js
import Ember from 'ember';
export default Ember.Service.extend({
counters: Ember.Object.create()
})
myService.counters
is a hash like:
{
clocks: 3,
diamons: 2
}
I want to add a computed attribute to this object such returns the sum of myService.counters.clocks
plus 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);
})
...
But the observer configuration is not accepted and I have the error:
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() {})`.
But if I make the proposed change:
// app/services/my-service.js
...
count: Ember.computed('counters.[]', function(){
return _.reduce(this.get('counters'), function(memo, num){ return memo + num; }, 0);
})
...
The count attribute is not updated.
The only way I can make it work is like this:
// 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);
})
...
How can I use any kind of wildcard for this situation?
@each
and []
are for observing array elements and arrays.
You can't use a wildcard because it would be a serious performance sink. There is a shorthand for multiple properties:
count: Ember.computed('counters.{clocks,diamons}', function() {
return this.get('counters').reduce((memo, num) => memo + num, 0);
})
I also updated the computed logic to use Array#reduce
, and an arrow function with implicit return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With