How to clone a backbone collection

21,820

Solution 1

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()));
});

Solution 2

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.

Solution 3

Use the Backbone Collection clone() method:

var clonedCollection = myCollection.clone();

Solution 4

Another option, if you need the following (which is what I was looking for when I found this question ;) ):

  • The copy of the collection should be of the same type as the original collection (e.g. you've created your own collection type that extends Backbone.Collection)
  • The copy of the collection should be created with the same options as the original
  • The models in the copy of the collection should be created using the model.clone() method

Code:

var models = original.map(function (model) { return model.clone(); });    
var options = _.clone(original.options);    
var copy = new original.constructor(models, options);

A generic clone method on Backbone.Collection would be awkward because there are always going to be subtleties around whether models and their nested objects get copied by reference or are themselves cloned. Requirements will vary wildly according to your scenario, so it's been left for you to write what you need.

Share:
21,820
Andreas Köberle
Author by

Andreas Köberle

Updated on November 22, 2020

Comments

  • Andreas Köberle
    Andreas Köberle over 3 years

    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.