Is there a way to easily clone Backbone Collection? I wonder why there is no build in method like for models. My problem is that I have a model holding a collection of childs. When I clone the model. I've still the collection of childs but only with their default values.
Backbone.Collection Collections are ordered sets of models. You can bind "change"events to be notified when any model in the collection has been modified, listen for "add"and "remove"events, fetchthe collection from the server, and use a full suite of Underscore.js methods.
Both can be appropriate in the same app, depending on the quantity of data involved, and the complexity of the UI. Nested Models & Collections It's common to nest collections inside of models with Backbone.
All "add"and "remove"events are now sent through the model, so that views can listen for them without having to know about the collection. Added a removemethod to Backbone.View. toJSONis no longer called at all for 'read'and 'delete'requests. Backbone routes are now able to load empty URL fragments.
Backbone doesn't include direct support for nested models and collections or "has many" associations because there are a number of good patterns for modeling structured data on the client side, and Backbone should provide the foundation for implementing any of them. You may want to…
Simplest way:
var cloned = new Backbone.Collection(original.toJSON());
where original
is the collection to clone.
Could always then extend Backbone's Collection
to add clone support w or w/o inheritance support.
What's your use case that you want to clone the collection?
There isn't a built in clone function for a collection because you do not want to clone the models within the collection. Cloning a model would cause there to be two separate instances of the same model, and if you update one model, the other one won't be updated.
If you want to create a new collection based upon a certain criteria, then you can use the collection's filter method.
var freshmenModels = studentsCollection.filter(function(student) {
return student.get('Year') === 'Freshman';
}
var freshmenCollection = new Backbone.Collection(freshmenModels);
To go ahead and clone the models in the collection, you can write the following code
var clonedCollection = new Backbone.Collection();
studentsCollection.each(function(studentModel) {
clonedCollection.add(new Backbone.Model(studentModel.toJSON()));
});
Use the Backbone Collection clone() method:
var clonedCollection = myCollection.clone();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With