This.set("prop", value) doesn't trigger a view change - but the prop does change


#1

Hi there,

I have the following logic in a component:

import Ember from 'ember';

export default Ember.Component.extend({
  selectedCats: [],
  actions: {
    selectCategory: function(category) {
      var myCats = this.get('selectedCats');
      myCats.push(category.id);
      this.set('selectedCats', myCats);
    }
  }
});

and the following view:

{{#each selectedCats as |cat|}}
{{cat}}
{{/each}}

selectCategory() is triggered when I click on something below. However, the view is not updated then. To get my view to update, I have to change selectCategory() to the following, which is functionnally identical but recreates a whole new array somewhere else with the same content:

  selectCategory: function(category) {
      var myCats = [];
      this.get('selectedCats').forEach(function(existingCat) {
        myCats.push(existingCat);
      });
      myCats.push(category.id);
      this.set('selectedCats', myCats);
    }

The only difference is that in one case, myCats is an Ember Array, in the other case it’s just a regular array. In both cases, if I console.log selectedCats at the end, I get the exact same result. Only the view does not get updated in the first case.

I would really like to know/understand why… :slight_smile:

Thanks! François


#2

You are using push. That wont’ work in ember. You have to use one of ember’s array methods, like pushObject.

your function can be replaced with:

selectCategory(category) {
  this.get('selectedCats').pushObject(category.id);
}