1

What is the preferred way, if any, to instantiate a Backbone model from an existing model, assuming that the model to be instantiated is of a derived type of the existing model?

The case I have in mind arises when dealing with nested models. For instance, let's say I am using DeepModel and I define a function on my "parent" model that returns this.get("childModel"). Now the child model is likely of type Backbone.Model but I would like it to be of type ChildModel which extends Backbone.Model. I have been doing this by literally copying over the interesting attributes one at a time. Surely there must be a better way...

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126

1 Answers1

2

You can create new instance of the same model by using Backbone.Model#clone() method or just using new model.constructor().

var ChildModel = Backbone.Model.extend({
    ...
});

var child = new ChildModel({ key: "value" });

var new_child = child.clone();

If we see the source of clone method:

clone: function() {
    return new this.constructor(this.attributes);
},

we can use the same approach to create new instance but with our data

var new_child = new child.constructor({ new_key: "new_value" });
Eugene Glova
  • 1,543
  • 1
  • 9
  • 12