Sachin Jain
Sachin Jain

Reputation: 21842

How to call the defaults method of parent model in backbone

I have created a ParentModel and few other models which extend ParentModel. Each ChildModel has some additional properties than ParentModel.

I want to call defaults method of ParentModel and get that JSON and add some additional properties and return the modified object from the defaults of ChildModel.

Here is my code:

var ParentModel = Backbone.Model.extend({
  defaults: function() {
    return {
      name: '',
      description: '',
      ruleType: '',
      creationDate: ''
    };
  }
});

var ChildModel = ParentModel.extend({
  defaults: function() {
    //Q: How to get the defaults from ParentModel and add one more property to json
  }
});

var c = new ChildModel({});

But I am unable to figure out How to call the defaults method of the class it is extending (ParentModel) ?

Upvotes: 2

Views: 293

Answers (2)

J.D.
J.D.

Reputation: 1843

Backbone lets you access the prototype of the parent through the __super__ property.

So you can call a parent method like this:

this.constructor.__super__.parentMethod.apply( this, arguments )

So in your case:

var ChildModel = ParentModel.extend({
    defaults: function() {
        return _.extend( 
            { extraProps: 'here' }, 
            this.constructor.__super__.defaults.apply( this, arguments )
        );
    }
});

Explanation:

  • __super__ is a "static" property, not a prototype property, so it must be accessed through this.constructor.__super__ instead of just this.__super__.
  • We use apply() here instead of just calling defaults() directly. This allows us to do two things. First, it lets us set the value that this will have inside of the parent defaults() method. That isn't important in your case, but it can be when other parent methods are being overridden. Then we use the second argument of apply() to pass along any arguments that were passed to the child function. Again, this is not important in your case, but may be useful for others.

Upvotes: 1

Robert Levy
Robert Levy

Reputation: 29073

_.extend({extraProps:here}, ParentModel.prototype.defaults)

Upvotes: 1

Related Questions