1

I am trying to copy a model from a backbone collection to another but problem is that only reference is being copies, that is if I change value of model in one collection the value is automatically changed for other collection. The problem is how do I make an exact copy of model object.

Thanks

ali asad
  • 1,329
  • 4
  • 17
  • 23
  • 1
    Try creating a deep copy: http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object – David Sulc May 30 '13 at 15:15

4 Answers4

1

I have tried all the methods of cloning but the result was not good because cid of the clonned model was becoming same which was causing problem. So I have applied this method

var widget = this.widgetsCollection.get(widgetId)
var newWidget=new Widget(widget.attributes);

This gives a copy with different cid.

enter image description here

ali asad
  • 1,329
  • 4
  • 17
  • 23
0

Try creating a deep copy, which will create a new object instance with the same values.

An example can be found in this SO thread: What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
David Sulc
  • 25,946
  • 3
  • 52
  • 54
0

There also exist a method clone in Backbone Model that creates a new copy with same attributes

this.widgetsActiveCollection.add(widget.clone());
ali asad
  • 1,329
  • 4
  • 17
  • 23
0

This is how I create a deep copy of the model

var newModel = new createModel(JSON.parse(JSON.stringify(oldModel)));
newCollection.add(newModel );
anandharshan
  • 5,817
  • 4
  • 34
  • 33