【问题标题】:Ember computed property on service服务上的 Ember 计算属性
【发布时间】:2015-10-06 17:24:04
【问题描述】:

我希望从服务对象中获得计算属性,但在这样做时遇到了麻烦。我有一个购物车服务和一条购物路线,允许客户挑选商品并将它们添加到购物车中。我将它们添加到购物车没有问题,但是当我尝试从控制器或路由添加计算属性时,它们永远不会在对象(购物车和 cartTotal)更改时触发。

这是购物车服务:

export default Ember.Service.extend({
  cart: [],
  currentTotal: 0,
  addToCart(product){
    // TODO add promise here
    this.get('cart').push(product);
    this.get('updateTotal')(this);
  },

  updateTotal: function(context){
    debugger;
    var total = 0;
    context.get('cart').forEach(function(product){
      total += parseInt(product.get('price'));
    }.bind(total));
    context.set('currentTotal', total);
  },
 ...

这是我的商店管理员:

const { service } = Ember.inject;

export default Ember.Controller.extend({
  cart: service('cart'),
  products: null,
  productGroupings: null,
  menus: null,
  currentMenu: Ember.computed.oneWay('cart.currentMenu'),
  menus: Ember.computed.oneWay('cart.menus'),
  cartTotal: Ember.computed.oneWay('cart.cartTotal'),
  ...

观察者设置属性以及使用别名代替“oneWay”也会失败。这在路线上也失败了。我目前正在运行 Ember 1.13.8。

谢谢!

【问题讨论】:

    标签: ember.js service ember-data ember-cli


    【解决方案1】:

    是的,这是可能的。您只是忘记在两个函数的末尾添加 .property():

    addToCart(product){
      // TODO add promise here
      this.get('cart').push(product);
      this.get('updateTotal')(this);
    }.property('cart', 'updateTotal'),
    

    【讨论】:

      【解决方案2】:

      刚刚意识到我忘记在推送周围添加 this.notifyPropertyDidChange。没有这个集合,计算的属性永远不会被触发。添加它可以解决问题。

      【讨论】:

        猜你喜欢
        • 2017-04-10
        • 1970-01-01
        • 2017-04-11
        • 1970-01-01
        • 2016-05-17
        • 1970-01-01
        • 1970-01-01
        • 2015-09-20
        • 1970-01-01
        相关资源
        最近更新 更多