这是一个老问题,但@nikoshr 和这个答案对我有帮助,所以我想添加我的贡献。
就我而言,我需要克隆一个包含嵌套集合的模型:
app.Collections.collection1 = Backbone.Collection.extend({
model: app.Models.model1,
clone: function() {
return new this.constructor(_.map(this.models, function(model) { var clone = model.clone().unset('id', {silent: true}).unset('idAttribute', {silent: true}); return clone.set('collection2', clone.get('collection2').clone()); }));
}
});
app.Collections.collection2 = Backbone.Collection.extend({
model: app.Models.model2,
clone: function() {
return new this.constructor(_.map(this.models, function(model) { return model.clone().unset('id', {silent: true}).unset('idAttribute', {silent: true}); }));
}
});
var clone = this.model.clone().unset('id', {silent: true}).unset('idAttribute', {silent: true});
clone.set('collection1', clone.get('collection1').clone());
var copy = this.model.collection.add(clone, {parse: true});
所以在你的情况下,我猜你可以做这样的事情:
app.Collections.collection1 = Backbone.Collection.extend({
clone: function() {
return new this.constructor(_.map(this.models, function(model) { return model.clone().unset('idAttribute', {silent: true}); }));
}
});
collection2.add(collection1.clone().models);