Reputation: 1349
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
Upvotes: 1
Views: 2795
Reputation: 6342
This is how I create a deep copy of the model
var newModel = new createModel(JSON.parse(JSON.stringify(oldModel)));
newCollection.add(newModel );
Upvotes: 0
Reputation: 1349
There also exist a method clone in Backbone Model that creates a new copy with same attributes
this.widgetsActiveCollection.add(widget.clone());
Upvotes: 0
Reputation: 1349
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.
Upvotes: 1
Reputation: 25994
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?
Upvotes: 0