计算子总计emberjs

鲁斯纳索诺夫

我创建一个购物车。我使用夹具适配器。我的模特

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 = [];

路线

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

还有我的控制器

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

我如何计算总价?

亚当

您可以将的reduceComputed属性放在一起sum以下是一些启发链接:基本上,您可以执行以下操作:

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

然后,在您的控制器中执行以下操作:

App.CartController = Em.ArrayController.extend({
    prices:     Ember.computed.mapBy('content', 'fullPrice'),
    totalPrice: Ember.computed.sum('prices')
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章