Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 271
fguillen Avatar asked Sep 26 '22 04:09

fguillen


1 Answers

@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.

like image 167
locks Avatar answered Oct 30 '22 23:10

locks