EmberJS how to observe changes in any hash object

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 - hash like:

{
  clocks: 3,
  diamons: 2
}

I want to add a computed attribute to this object, thus returning the sum myService.counters.clocksplusmyService.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 an 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 to make it work:

// 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 template for this situation?

+4
source share
1 answer

@eachand []are designed to observe array elements and arrays.

, . :

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

Array#reduce .

+3

All Articles