2

I create a shop cart. I using fixture adapter. My models

App.Clothing = DS.Model.extend({
      name:     DS.attr('string')
    , category: DS.attr('string')
    , img:      DS.attr('string')
    , price:    DS.attr('number')
    , num:      DS.attr('number')
    , fullPrice: function(){
        return this.get('price') + " $";
    }.property('price')
})

App.CartRecord = App.Clothing.extend({
    numInCart:DS.attr('number',{defaultValue:1})
    , fullPrice: function(){
        return this.get('price')*this.get('numInCart');
    }.property('numInCart','price')
})
App.CartRecord.FIXTURES = [];

Route

App.CartRoute = Em.Route.extend({
    model: function(){
        return this.store.find('cartRecord');
    }
})

And my controller

App.CartController = Em.ArrayController.extend({
    totalPrice: 0
});

How i can calculate a total price?

1 Answer 1

3

You can put together a reduceComputed property for sum. Here are a few links for inspiration: one, two, and three. Basically, you can do something like this:

Ember.computed.sum = function (dependentKey) {
  return Ember.reduceComputed.call(null, dependentKey, {
    initialValue: 0,

    addedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
      return accumulatedValue + item;
    },

    removedItem: function (accumulatedValue, item, changeMeta, instanceMeta) {
      return accumulatedValue - item;
    }
  });
};

Then, in your controller do something like this:

App.CartController = Em.ArrayController.extend({
    prices:     Ember.computed.mapBy('content', 'fullPrice'),
    totalPrice: Ember.computed.sum('prices')
});
2
  • But Ember.computed.sum('@this.@each.fullPrice') return the list of clotheis in cart. If i render this in view <p>Subtotal {{totalPrice}}</p> On page i give: 0<App.CartRecord:ember490:1><App.CartRecord:ember492:2><App.CartRecord:ember493:3>
    – rusnasonov
    Jan 17, 2014 at 16:13
  • I updated it to use a new dependent key. I've never actually tried the @this.@each.fullPrice style syntax. Let me know if this works better. Here's a jsFiddle of it in action
    – Adam
    Jan 17, 2014 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.