I'm working with backbone.js models, so I don't know if my question is particular to the way backbone handles cloning or if it applies to javascript in general. Basically, I need to clone a model which has an attribute property assigned an object. The problem is that when I update the parent or clone's attribute, the other model is also updated. Here is a quick example:
var A = Backbone.Model.extend({});
var a = new A({'test': {'some': 'crap'}});
var b = a.clone();
a.get('test')['some'] = 'thing';
// I could also use a.set() to set the attribute with the same result
console.log(JSON.stringify(a))
console.log(JSON.stringify(b))
which logs the following:
{"test":{"some":"thing"}}
{"test":{"some":"thing"}}
I would prefer to clone a such that b won't be referencing any of its attributes. Any help would be appreciated.
Backdone does not do a deep-clone, but only clone first level attributes. You have to clone the values yourself (when it is a hash or array for exemple).
You could do
var A = Backbone.Model.extend({});
var a = new A({'test': {'some': 'stuff'}});
var b = new A(a.model.toJSON());
Adapted from this answer: How to clone a backbone collection
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