Calculate sub total emberjs

我们两清 提交于 2019-12-11 02:33:53

问题


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:


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')
});


来源:https://stackoverflow.com/questions/21189670/calculate-sub-total-emberjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!