Matt Sweetman

Latest articles

Base class for Backbone

The core Backbone objects (Model, View, Collection and Router) have a convention for construction and initialization that make them feel more like traditional classes. This convention helps provide a degree of consistency across the Backbone framework. In a large project you might find yourself wanting to use it for all objects, not just Backbone ones, in which case the following snippet of code might be of use to you.

Backbone.Class is a convention for creating any Backbone-style object and follows several rules laid out by other Backbone classes:

This is the minimum existing Backbone classes provide so it's perfect as a basis for our own. You can add the base class onto Backbone itself so it can be used throughout your apps:

// Create a new constructor function and call initialize on instantiation
// This follows the convention laid out by other Backbone classes
Backbone.Class = function(options) {
  this.cid = _.uniqueId('class');
  this.initialize.apply(this, arguments);
};

// Extend the prototype with Events and a default initialize function
_.extend(Backbone.Class.prototype, Backbone.Events, {
  initialize: function(){}
});

// Add the extend method to allow us to create subclasses of the object
// Steal the reference from Model as it's inaccessible outside Backbone
Backbone.Class.extend = Backbone.Model.extend;

The only slight oddity is how we must borrow extend from one of other Backbone classes. In this case we've chosen Backbone.Model, but View, Router and Collection are equally valid. Unfortunately Backbone doesn't make the extend method available publicly so this is the only solution.

The base class can then be used in a similar way to other Backbone classes:

var LoaderUtility = Backbone.Class.extend({
  initialize: function(options) {
    this.timeout = options.timeout;
  }
});

var loaderUtility = new LoaderUtility({timeout: 5000});

You might find this adds a bit of consistency to your code base, especially having a uniform way to name constructor functions.