ORL
ORL

Reputation: 618

In Ember how do I update a view after the ArrayController content is modified?

I'm just starting with ember so forgive me if this question seems daft. I have an ArrayController that holds a list of people with the attribute name. I'm using the following handlebars call to create textfields for each name in the content array:

{{#each App.Controller}}
{{view Em.TextField placeholder="Name" valueBinding="name" }}
{{/each}}

this is working as expected. I first initialize my content array with several names and a textfield appears for each entry. However when I use pushObject to add a person to the content array a new textfield is not added! Using the console I can see that the people are being added to content, the view is simply not changing. Stranger still, if I add people in the following manner everything works as expected:

this.pushObject(newPerson);
var copy = this.get('content');
this.set('content',[]);
this.set('content',copy); 

When I add people this way I get another textfield for the newly added person. The ember documentation says pushObject() is KVO-compliant, doesn't that mean it should update the dependencies and the view should update? Do I need to call rerender() or some other function to make pushObject() update the view or do I have to copy the array each time I want to update the view? Thanks!

Upvotes: 2

Views: 603

Answers (2)

fengyun liu
fengyun liu

Reputation: 101

I encounter similar problems, when I use this.pushObject to add a new item, the view only updates if the item is the first object.

Later I tried with this.insertAt, it works well without any problem.

Upvotes: 0

ORL
ORL

Reputation: 618

So I figured out the issue. In my init function for the Controller I was simply adding elements to the content array like this

App.Controller = Em.ArrayController.create({
content: [],

init: function(){
    this.insertNew();
},


insertNew: function(){
    var t = App.Person.create({
        name:"test"
    });
    this.pushObject(t);
},   

});

This code did not change the view when insertNew was called (though the initialization worked). By adding this.set("content",[]) to my init function insertNew behaved as expected. Here's the working code:

App.Controller = Em.ArrayController.create({
content: [],

init: function(){
    this.set("content",[]);
    this.insertNew();
},


insertNew: function(){
    var t = App.Person.create({
        name:"test"
    });
    this.pushObject(t);
},   

});

I had thought the first content:[] line meant I did not need to set content again later, but it seems that when initializing the array you have to set it again.

Upvotes: 0

Related Questions