Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember, my template doesn't update on property change

Why doesn't my template get updated when I change the property it is rendering? The documentation states that {{each}} is bindings-aware, but there's obviously something to it that I am not aware of.

Like everything in Handlebars, the {{#each}} helper is bindings-aware. If your application adds a new item to the array, or removes an item, the DOM will be updated without having to write any code.

Here's my controller

App.MaintemplateController = Ember.Controller.extend({
  alist: ['foo', "bar"],        
  actions : {   
    addel: function(){
            this.alist.push('xpto');
            console.log(this.alist);
     }
   }
});

In my template I have the following code.

{{#each alist}}
    <li>{{.}}</li>
{{/each}}
<button {{action 'addel'}}>Add element</button>

The data is properly rendered, and when I click the button it does append elements to the property, but the template doesn't refresh. Why? How do I keep it in sync with my data?

like image 356
Pico Avatar asked Sep 05 '13 08:09

Pico


1 Answers

Your template is not updating because you are using plain vanilla javascript .push instead of the by ember provided .pushObject and .removeObject respectively. Ember by default extends the array prototype to make it play nicely in a binding aware environment.

So to make your template update you should do:

App.MaintemplateController = Ember.Controller.extend({
  alist: ['foo', "bar"],        
  actions : {   
    addel: function(){
      this.get('alist').pushObject('xpto');
      console.log(this.get('alist'));
    }
  }
});

The important line here is this.get('alist').pushObject('xpto'); Furthermore you should always use .get() and .set() to access objects in ember otherwise the binding mechanism will not be aware of changes made to the object.

Hope it helps.

like image 79
intuitivepixel Avatar answered Sep 29 '22 01:09

intuitivepixel