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 attri开发者_如何转开发bute 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
var A = Backbone.Model.extend({});
var a = new A({'test': {'some': 'stuff'}});
var b = a.clone();
b.attributes = $.extend(true, {}, b.attributes);
// try to overwrite "some" without affecting "a" model
var someStuff = {'test': {'some' : 'other stuff'}};
b.set(someStuff);
console.log(a.toJSON());
console.log(b.toJSON());
http://jsfiddle.net/RLWzm/
精彩评论