Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a javascript/backbone.js cloned model from sharing attributes

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.

like image 587
user2095627 Avatar asked Mar 14 '26 10:03

user2095627


2 Answers

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).

like image 123
Julien Avatar answered Mar 17 '26 00:03

Julien


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

like image 35
mooreds Avatar answered Mar 17 '26 00:03

mooreds