How do you clone an entire backbone model?

125 views Asked by At

I have a large backbone model that is fairly complex and contains nested arrays and objects.

If I clone using the backbone method, like this:

 var model2 = model1.clone();

It will clone the top-level properties and arrays, but anything deeper, is not cloned at all.

For example, it will clone these model properties just fine:

id: 29832, title: ExtremeGaming, type: "9a", users: [0: "advanced", 1: "elite"]

But more complex properties are ignored, like this(this is what I see in console.log. In backbone, the model is games.:

games: 
   adventure: 
      models: Array(1)
          0: child
             attributes:
                 title: "PitFall"
                 year: "(old) 1981"

Is there a backbone way of cloning the entire backbone model?

Thanks!

2

There are 2 answers

0
Allan Bazinet On BEST ANSWER

The Backbone crew discourage storing anything other than primitives in models, and therefore if you're going to do so, it's on you to handle it.

https://github.com/jashkenas/backbone/issues/3457

One can use the lodash cloneDeep() function for this, e.g.,

const model2 = new Model(_.cloneDeep(model1.attributes));

There are several alternatives to cloneDeep(); depending on your supporting library cast of characters, there may be a work-alike already available to you. For example, babel and core-js as of late have the usual auto-polyfill support for structuredClone(), so if you're already set up for that, it'd be my first choice now.

0
Ahmed Ibrahim On

backbone is cloning by creating new instance with a copy of the attributes, so as long as the property is on the attribute, it should be safe to be cloned

from backbone source code

// Create a new model with identical attributes to this one.
clone: function() {
   return new this.constructor(this.attributes);
},