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')
};
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With