How to change elements in an array controlled by Ember Controller?

I probably miss something really stupid (Ember newbie), but I can’t figure out how to change the array that my Ember Controller is managing except to set up a completely new array.

For instance. I have the following test function in my controller. When the user clicks, I want to change each element of the managed array (or it can be a separate element) with a new value.

I understand that you have to go through the “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 return. But for some reason Ember complains about the 4th line, where I change the contents of temp [i] .desc, saying that I need to use Ember.Set. I suggested that I could change the “stand-alone” copy and then install it back, but not-go, and I cannot understand why. Other array operations seem to work, such as shift / unshift / pop.

+5
source share
1 answer

Your approach does not look very bright. This code will 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 not use the direct access approach?

set() Ember . , , , . - , , .

, : ArrayController itemList. itemList . , , .

App.ItemListController = Ember.ArrayController.extend({
    content : null, //set your itemList into this property
    clickHandler:function(e){
        this.get("content").setEach("desc", "CANCELLED");
    }
});
+11

All Articles