2013-04-18 53 views
2

林與收集和模型工作:臨時骨幹收集編輯模式

在一個地方
var StuffCollection = Backbone.Collection; 
var StuffModel = Backbone.RelationalModel; 

我作出這樣的收集與模型實例:

var stuffCollection = new StuffCollection(); 
// do stuff here to load a bunch of models 

在另一個地方,我想克隆該集合編輯而不編輯原始:

var tempStuffCollection = new StuffCollection(); 
tempStuffCollection.reset(stuffCollection.models); 
// do stuff here to edit the collection 

但是當我編輯m odels在tempStuffCollection他們編輯stuffCollection 所以不是我想這樣的:

var tempStuffCollection = new StuffCollection(); 
tempStuffCollection.reset(stuffCollection.toJSON()); 
// do stuff here to edit the collection 

所以它似乎像所有的引用都被刪除......但不!當我在tempStuffCollection中編輯模型時,它仍然在stuffCollection中更改它們!

我該如何分離兩個模型集?

回答

2

您需要克隆該集合。這是一種方法。

var tempStuffCollection = new StuffCollection(); 
stuffCollection.each(function(model) { 
    tempStuffCollection.add(new Backbone.Model(model.toJSON())); 
}); 
+0

您的意思是:tempStuffCollection.add(new Backbone.Model(model.toJSON())); – Kev

+0

確實:)進行編輯。對於那個很抱歉。 –

+0

這不是爲我工作,但我也使用骨幹關係模型...我得到這個錯誤:不能實例化每個類型相同的ID多個Backbone.RelationalModel! – Kev

0

你的問題似乎是你不能有兩次相同的模型。所以,你可以這樣做:

var tempStuffCollection = new StuffCollection(); 
stuffCollection.each(function(model) { 
    var json = model.toJSON(); 
    json._id = json.id; // _id is maybe a reserved attribute, change it if needed 
    delete json.id; 
    tempStuffCollection.add(new Backbone.Model(json)); 
}); 

然後做逆運算...

0

它可能並不適合你的工作的原因是,骨幹關係的數字了,你把款進臨時集合與原始集合中的集合相同,因此它使用舊的模型。它通過查看每個模型的idAttribute來完成此操作。

因此,您可以嘗試在將模型放入臨時集合中時更改模型的idAttribute名稱,然後在完成時更改它們。

也許像這樣把他們變成你的臨時集合:

var parsedStuffCollection = stuffCollection.toJSON() 

_.each(parsedStuffCollection, function(stuffAttributes){ 
    stuffAttributes.tempIDAttribute = stuffAttributes.myIdAttribute; 
    delete stuffAttributes.myIdAttribute; 
}) 

var tempStuffCollection = new StuffCollection({parsedStuffCollection}); 

然後,只需做反向改回

編輯:剛剛意識到這是做同樣的事情Loamhoof的回答