4

I'm .clone() -ing a collection so that I can use a splice loop on it and not interfere with the original. Are the models in cloned array originals or copies?

What I need is a copy of the array with the original models in it.

Thanks for any info!

boom
  • 10,856
  • 9
  • 43
  • 64

1 Answers1

8

You will get the same models as the source collection wrapped in a new collection of the same type.

Here is the implementation of collection.clone:

   clone: function() {
      return new this.constructor(this.models);
    },

Or if you prefer a deep clone, override Backbone.Collection.clone

clone: function(deep) {
  if(deep) {
    return new this.constructor(_.map(this.models, function(m) { return m.clone(); }));
  }else{
    return Backbone.Collection.prototype.clone();
  }
}

http://jsfiddle.net/puleos/9bk4d/

Scott Puleo
  • 3,684
  • 24
  • 23
  • No worries. If you ever get hung up just read the annotated source. http://backbonejs.org/docs/backbone.html – Scott Puleo May 07 '13 at 16:36
  • why would I use this? I mean, usually, if I clone things, I want them not to hold *any* reference to the old collection, *especially* not the models! – raffomania Aug 22 '13 at 20:58
  • 1
    @raffomania There are times where clone comes in handy. Client side filtering, paging and sorting to name a few. If you prefer a deep clone just override backbones clone. – Scott Puleo Aug 23 '13 at 16:52