Backbone.js view inheritance

The easiest way to inherit a view is to do what other people have already suggested in the comments:

var Pannel = Backbone.View.extend({
});

var PannelAdvanced = Pannel.extend({
});

But like you’ve noted in your comments, if you have an initialize method in Pannel, then it won’t be called if you also have an initialize method in PannelAdvanced, so you have to call Pannel’s initialize method explicitly:

var Pannel = Backbone.View.extend({
   initialize: function(options){
      console.log('Pannel initialized');
      this.foo = 'bar';
   }
});

var PannelAdvanced = Pannel.extend({
   initialize: function(options){
      Pannel.prototype.initialize.apply(this, [options])
      console.log('PannelAdvanced initialized');
      console.log(this.foo); // Log: bar
   }
});

It’s a bit ugly because if you have a lot of Views that inherit from Pannel, then you’ll have to remember to call Pannel’s initialize from all of them. Even worse, if Pannel doesn’t have an initialize method now but you choose to add it in the future, then you’ll need to go to all of the inherited classes in the future and make sure they call Pannel’s initialize. So here’s an alternative way to define Pannel so that your inherited views don’t need to call Pannel’s initialize method:

var Pannel = function (options) {

    // put all of Panel's initialization code here
    console.log('Pannel initialized');
    this.foo = 'bar';

    Backbone.View.apply(this, [options]);
};

_.extend(Pannel.prototype, Backbone.View.prototype, {

    // put all of Panel's methods here. For example:
    sayHi: function () {
        console.log('hello from Pannel');
    }
});

Pannel.extend = Backbone.View.extend;


// other classes inherit from Panel like this:
var PannelAdvanced = Pannel.extend({

    initialize: function (options) {
        console.log('PannelAdvanced initialized');
        console.log(this.foo);
    }
});

var pannelAdvanced = new PannelAdvanced(); //Log: Pannel initialized, PannelAdvanced initialized, bar
pannelAdvanced.sayHi(); // Log: hello from Pannel

Leave a Comment