2012-08-15 100 views
0

我確信我必須在這裏丟失一些明顯的東西:我創建了3個對象,每個對象都具有一個設置爲ArrayController的屬性。當我添加的每個新對象ArrayController實例共享內容從以前的控制器,而不是作爲一個唯一的實例:Ember.ArrayController.create()不返回唯一的實例

http://jsfiddle.net/w6DKR/3/

在我的例子,我可以解決這個問題的唯一辦法是做this.set('content', []);在ArrayController init方法。

回答

3

初始化(!和一個常見的錯誤)

其中最常見的錯誤就是認爲他們將屬性傳遞給實例而不是原型。例如:

var Person = Ember.Object.extend({ 
    chromosomes: ["x"] // CAREFUL !!!!! 
}); 

var joe = Person.create(); 
joe.get("chromosomes").push("y"); 

var jane = Person.create(); 
jane.get("chromosomes").push("x"); 

// Joe and Jane are all mixed up?!?!?!?! 
console.log(joe.get("chromosomes")); // x, y, x 
console.log(jane.get("chromosomes")); // x, y, x 

爲什麼會發生這種染色體突變?當我們在定義Person類時將數組添加到原型時,問題就開始了。然後該數組與每個從Person實例化的對象共享。

我們應該如何處理?

var Person = Ember.Object.extend({ 
    chromosomes: null, 
    init: function() { 
    this._super(); 
    this.chromosomes = ["x"]; // everyone gets at least one X chromosome 
    } 
}); 

var joe = Person.create(); 
joe.get("chromosomes").push("y"); // men also get a Y chromosome 

var jane = Person.create(); 
jane.get("chromosomes").push("x"); // women get another X chromosome 

// Hurray - everyone gets their own chromosomes! 
console.log(joe.get("chromosomes")); // x, y 
console.log(jane.get("chromosomes")); // x, x 

在聲明類中的對象或數組,您通常要與在init()函數每個實例一起對它們進行初始化。通過這種方式,每個對象都將接收其自己的唯一對象和數組實例。還要記得在init()中調用this._super(),以便在原型鏈中調用init()。

當然,如果要將對象或數組直接保存在原型中,如果它們的意圖在各個實例之間保持不變,那沒有什麼問題。實際上,一種常見的模式是在原型中保留一個默認設置,然後在init()中爲每個實例重複一次。一旦您意識到如何創建和初始化對象,這些模式很容易實現。

複製文章:http://www.cerebris.com/blog/2012/03/06/understanding-ember-object/

2

確實,您通常不希望在.extend({...})塊內設置content: [],因爲每個實例將共享相同的陣列。據我所知,這是可以接受的,甚至可能是共同的,圖案Ember.js:初學者灰燼

App.MyController = Ember.ArrayController.extend({ 
    content: null, 
    init: function() { 
     this._super(); 
     this.set('content', []); 
    }, 
    // ... 
});