1
votes

I am trying to create some computed properties with an Ember ObjectController and am experiencing some difficulties. My object (Baz) contains an array of objects (Foo). Each Foo has some key/value pairs, let's call them alpha and beta.

Using code like this:

App.BazController = Ember.ObjectController.extend({
    total: function() {
        return this.get('foos').getEach('alpha').reduce(function(accum, item) {
            return accum + item;
        }, 0);
    }.property('[email protected]')
});

I can calculate the sum of every Foo object's 'alpha' property but I would like to calculate values between specific Foos, ideally selected by their built-in ID. I have tried a fairly wide variety of expressions to try and select an individual Foo object out of the array but I can't seem to figure it out.

Can this be accomplished within an ObjectController or is this the wrong place to try and compute such values?

Any help from code to a conceptual walkthrough would be greatly appreciated.

Cheers, Allen

1

1 Answers

2
votes

You can access properties of the item in the reduce method while building up the total. For instance to find total of products but only if they are inStock and onSale, you can use.

totalByReduce: function() {
  return this.get('model').reduce(function(total, product) {
    if (product.get('inStock') && product.get('onSale')) {
      return total + product.get('price');
    } else {
      return total;
    }
  }, 0);
}.property('model.@each')

Likewise if you are doing the filtering in multiple stages, ie:- filtering then reducing, you can have 2 different computed properties that depend on each other. For instance, if you only display products that are inStock and onSale,

saleProducts: function() {
  return this.get('model').filter(function(product) {
    return product.get('inStock') && product.get('onSale');
  });
}.property('model.@each'),

Then to get the total of saleProducts you can setup a 2nd computed property like,

total: function() {
  return this.get('saleProducts').reduce(function(total, product) {
    return total + product.get('price');
  }, 0);
}.property('saleProducts.@each'),

Here's a jsbin example.