Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute length of a model

I have this productsCount computed property which should count all products but it always returns a 0. Why is that and how can I fix it?

controller.js

productsCount: Ember.computed('model.products', function() {
  var products = this.get('model.products');
  return products.get('length');
}),

route.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return {
      products: this.store.find('product')
    };
  }
});
like image 426
wintermeyer Avatar asked Jul 02 '15 17:07

wintermeyer


1 Answers

The model.products passed in your computed property, will just trigger when this.get('model').set('products', [...]) is called. But because products is an array like object the length property probably is changed when someone call products.pushObject(...) which will not make your computed property recompute because the products array reference isn't changed, just your contents.

To fix this you have to add .length to your computed property dependent key, like so:

productsCount: Ember.computed('model.products.length', function() {
  return this.get('model.products.length');
})

Since you're just aliasing an property, you can take advantage of Ember.computed.alias, and simplify your code to:

productsCount: Ember.computed.alias('model.products.length')

There are other very useful computed macros in Ember.computed.* you may want to give a look in the docs for further information

like image 83
Marcio Junior Avatar answered Oct 27 '22 20:10

Marcio Junior