Ember.computed.filterBy question



Can anyone please explain is there any differences between these two productsPremiumShown properties? I believe they should be the same, but I’m receiving different results for hasPremiumProducts property.

App.Some = DS.Model.extend(Ember.Validations, {
  products: DS.hasMany('product', {async: true}),
  productsShown: Ember.computed.filterBy('products', 'shown', true),

  // productsPremiumShown: Ember.computed.filterBy('productsShown.[]', 'is_premium', true),

  productsPremiumShown: function() {
    return this.get("productsShown").filterBy('is_premium', true);

  hasPremiumProducts: Ember.computed.notEmpty('productsPremiumShown.[]'),



sorry for interruption. Ember.computed.filterBy(‘productsShown.[]’

square brackets here are excess


The source of Ember.computed.filter is here. As you can see it uses Ember.arrayComputed, which updates property with “one at a time” semantics.

What does “one at a time” mean?

Look at the common property example:

productsPremiumShown: function() {
  return this.get("productsShown").filterBy('is_premium', true);

It means, when the productShown array is changed, the property is fully recomputed. Which means running this.get("productsShown").filterBy('is_premium', true).

In this code, everytime the property is changed, it iterates the whole array to get the filtered result.

If we have a way, when a new item is added to productsShown array, the filter function is only executed for that item, if it matches, then add that item to productsPreminumShown array, otherwise do nothing. That should be better.

This is “one at a time” way, and is what Ember.computed.filter do for you.

For details you can check Ember.arrayComputed and Ember.reduceComputed.

Actually, Ember.computed.filter is a syntax suger for Ember.arrayComputed, and Ember.arrayComputed is a syntax suger for Ember.reduceComputed. So if you understand Ember.reduceComputed, you understand all of them.


thanks for explanation.