Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify elements in an array that is managed by an Ember Controller?

Tags:

ember.js

I'm probably missing something really silly, (Ember newbie) but I can't figure out how to modify an array that's under the management of my Ember Controller, other than to set an entirely new array.

For example. I have the following test function in my controller. When the user clicks, I want to modify each element of the controlled array (or it could be an individual element) with a new value.

I understand that you're supposed to go through "set" to make the changes known to Ember, so I thought this would work:

clickHandler:function(e){
    var temp = this.get("itemList").copy(); // copy it
    for (var i = 0; i < temp.length; i++) { 
        temp[i].desc = "CANCELLED";     // change it
    }
    this.set('itemList', temp); // put it back
}

I make a copy of the array, modify it, and then set it back. But somehow Ember complains about the 4th line, where I modify the contents of temp[i].desc, saying I have to use Ember.Set. I assumed I could modify the "offline" copy and then set it back, but no-go and I can't figure out why. Other array operations, like shift/unshift/pop seem to work.

like image 300
J Sprague Avatar asked Feb 22 '13 21:02

J Sprague


1 Answers

Your approach does not look very emberish. This code would work:

clickHandler:function(e){
    var itemList = this.get("itemList");
    itemList.forEach(function(item){ // for iterating over an array, always use the forEach function
        item.set("desc", "CANCELLED"); // you have to call this set()-function to make changes to an Ember Object
    });
}

Why do you need to call the set()-method and can't use your direct access approach?

The set()-method enables Ember to perform its autobinding magic. When this method is called, it schedules all the stuff that needs to be performed on the objects that depend on the modified property. The easiest example is a template displaying that given property that would need an update.

Here a possible improvement on the code above to make even more emberish: You could use an ArrayController to manage your itemList. In this case you would set your itemList as the content property of the controller. You will notice that lots of tutorials leverage this controller if dealing with an array.

App.ItemListController = Ember.ArrayController.extend({
    content : null, //set your itemList into this property
    clickHandler:function(e){
        this.get("content").setEach("desc", "CANCELLED");
    }
});
like image 148
mavilein Avatar answered Sep 27 '22 16:09

mavilein