How to call overwritten methods of parent classes in Backbone.js

Updated . Posted . Visible to the public.

When you are working with Backbone models and inheritance, at some point you want to overwrite inherited methods but call the parent's implementation, too.
In JavaScript, there is no simple "super" method like in Ruby -- so here is how to do it with Backbone.

Example

BaseClass = Backbone.Model.extend({
  initialize: function(options) {
    console.log(options.baseInfo);
  }
});

MyClass = BaseClass.extend({
  initialize: function(options) {
    console.log(options.myInfo);
  }
});

new MyClass({ myInfo: 'Hello World.', baseInfo: 'Hello Universe!' });

When you do that, MyClass will only run its own initialize method, and you'd get this console output:

Hello World.

How to super

But we want initialize of BaseClass to run as well -- and if you want to call a method in JavaScript, you need to do exactly that.

Backbone offers a shortcut that is not too ugly, and looks like this:

MyClass = BaseClass.extend({
  initialize: function(options) {
    console.log(options.myInfo);
    this.constructor.__super__.initialize.apply(this, arguments);
  }
});

That will call the parent's initialize method with the arguments that your method received. The console output is now what we want:

Hello World.
Hello Universe!

If you want to have a different method signature, you may pass a different array than arguments, or just use call:

MyOtherClass = BaseClass.extend({
  initialize: function(foo, bar, baz) {
    // ...
    this.constructor.__super__.initialize.call(this, { baseInfo: bar });
  }
});

Old versions of Backbone.js

Apparently there was no this.constructor in older versions of Backbone.js, and you'd have to explicitly name your parent class (which is a bit less robust). The approach shown above has been used on Backbone 1.1 and probably works for you as well. If you run into trouble, you might want to check a StackOverflow about accessing the parent class Show archive.org snapshot .

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-02-12 09:56)