Ember.computed.sum

Let’s have models:

Model: basket

export default DS.Model.extend({
  fruits: DS.hasMany('fruit', { async: true }),

  fruitCountArray: Ember.computed.mapBy('fruits', 'count'),
  totalFruitCount: Ember.computed.sum('fruitCountArray')
});

Model: Fruit

export default DS.Model.extend({
  name: DS.attr('string'),
  count: DS.attr('number')
});

Jsbin with working example. Can someone explain why totalFruitCount shows correct amount when page loads, but incorrect when value is updated by using given {{input}}. Is it because I’m missing something or it’s just how it works?

As far as I can tell, its something with incorrect type, after value modification totalFruitCount show appended array values of fruitCountArray. I can easily fix it by implementing my own computed property with explicit parseInt (doing exactly same as demo if parseInt isn’t used) such as:

totalFruitCount: Ember.computed('fruits,@each.count', function() {
  let sum = 0;
  this.get('fruits').forEach(fruit => {
     sum += parseInt(fruit.get('hours'));
  });
  return sum;
})

But it feels wrong to me when there is already computed property just for this use-case. I’m using Ember 2.3.0 and Ember Data 2.3.0.

the problem is due to the array construction at

Find a suitable way to construct a numerical array or do it on your own