Computed "Helpers" With @each

I’ll start off by saying I’m new to Ember so if this is supported in another way then I welcome clarification.

I ran into a use case where I needed the total of values from related ED models. However, I discovered that I basically needed to loop through each relation to add its value to the total, using reduce:

totalNumber: function(){
    return this.get('relatedModels').reduce(function(total, relation){
        return total + relation.get('numberValue');
    }, 0);

But wouldn’t it be great if we could reduce that to just one line using the Ember.computed.sum helper?

totalNumber: Ember.computed.sum('relatedModels.@each.numberValue')

Doesn’t seem to work for me, but again maybe I’m just doing it wrong. I would imagine other computed helpers would benefit from this functionality as well.

Although I still cannot figure out if this is supported already, I’ve found a two line solution:

allNumbers: Ember.computed.mapBy('relatedModels', 'numberValue'),
totalNumber: Ember.computed.sum('allNumbers')

Although it would still be great if @each worked in sum(), I don’t need the allNumbers property for anything else…

Thoughts? I feel like the lack of discussion means this is a RTFM moment or such, which I’m fine with if that’s the case.

I think what you’re looking for is this…it’s behind a beta feature flag called composable-computed-properties.

This would enable you to do (note: haven’t tested this):

totalNumber: Ember.computed.sum( Ember.computed.mapBy("relatedModels", "numberValue") )

@Spencer_Price’s suggestion looks like what you’re looking for. Did it work for you @Panman8201?

Yes, that does work when enabling the feature flag. It certainly is a step in the right direction, thanks for bringing it up! It actually brings up a thought, could the @each tokens in the dependancyKey automatically be converted to a mapBy computed helper.?. I’m not too familiar with the inner workings of Ember just yet, but would certainly be willing to dig into it if someone could point me in the right direction. It just seems like it should naturally work as the “Ember way”.