Backbone.js Super Syntax Sugar DRAFT!

published:
2014.04.19
topics:
javascript

The MVC / MV* library Backbone.js has an extendable class-like system of objects. However, in their official documentation, the only mention they make to calling a parent / super method of a Collection, View, or Model that you've extended is via the prototype chain. From their example:

var Note = Backbone.Model.extend({
    set: function (attributes, options) {
        Backbone.Model.prototype.set.apply(this, arguments);
        // other stuff ...
    }
});

What they didn't document is that they assign a property __super__ to an object's constructor that is equal to the parent's prototype. So you can actually do this instead:

var Note = Backbone.Model.extend({
    set: function (attributes, options) {
        this.constructor.__super__.set.apply(this, arguments);
        // other stuff ...
    }
});

Now we don't need a specific named reference to our parent, which is very nice. I personally like to go a step further and create my own base Model/View/whatever that adds a tiny bit more syntax sugar for us:

var BaseModel = Backbone.Model.extend({
    constructor: function () {
        this._super = this.constructor.__super__;
        Backbone.Model.apply(this, arguments);
    } // constructor()
});

var Note = BaseModel.extend({
    set: function (attributes, options) {
        this._super.set.apply(this, arguments);
        // other stuff ...
    }
});

It is possible to take this even further where you automatically wrap each method in a closure that redefines this._super to actually be the parent method directly so you can just do this._super.apply(this, arguments); inside of any method. I do think that's neat, and several of the JavaScript libraries that use this kind of extends pattern for JavaScript objects do actually do that. But I'm personally content with my above solution in the context of Backbone.