Computed property of service


#1

Hi!

I was hoping to have a computed property off of a service object and have had trouble doing so. I have a shopping cart service and a shop route which allows customers to pick items and add them to the cart. I have no problem adding them to the cart, but when I try to add a computed property from the controller or route, they never fire when the objects (cart and cartTotal) change.

Here’s the cart service:

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

And here’s my shop controller:

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'),
  ...

It also fails with observers setting the properties as well as using alias inplace of ‘oneWay.’ This also fails on the route. I’m currently running Ember 1.13.8.

Thank you!


#2

Just realized that I forgot to add this.notifyPropertyDidChange around the push. Without the set, the computed properties never fired. Adding that fixed it right up.


#3

push is unobserved, you must use pushObject