Ember, my template does not update when the property changes

Why is my template not updated when I change the property that it executes? The documentation states that {{each}} is a binding to a binding, but obviously something I don’t know about.

Like everything in Handlebars, the {{#each}} helper is bindings. If your application adds a new element to an array or deletes an element, the DOM will be updated without writing code.

Here is 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 displayed correctly, and when I click the button, it adds elements to the property, but the template is not updated. What for? How to keep synchronization with my data?

+6
source share
1 answer

Your template is not updated because you use plain vanilla javascript .push instead of ember provided .pushObject and .removeObject respectively. Ember extends the prototype of the array by default so that it plays well in a binding-enabled environment.

So, in order to update your template, you must 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'); In addition, 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 this helps.

+15
source

Source: https://habr.com/ru/post/953217/


All Articles