Extending Backbone.js constructors, the easy way

One thing that really is really annonying with backbone 1.1 is the fact that the options are not passed has this.options anymore in the Backbone.View.

Well simply enough we can add this (or anything else) in the view constructor.

// Compatibility override - Backbone 1.1 got rid of the 'options' binding
// automatically to views in the constructor - we need to keep that.
Backbone.View = (function(View) {
   return View.extend({
        constructor: function(options) {
            this.options = options;
            View.apply(this, arguments);
        }
    });
})(Backbone.View);

You can also augment the constructor with anything you need. This is useful, for example, if all views need to call some functions when initialized, or if you need to set some data on all views.

You could also use this pattern to augment any Backbone constructor, the possibilities are endless!

Cedric Dugas is a front-end veteran with more than 9 years under the belt, between his open source projects & entrepreneurial ambitions he is a product architect at CakeMail. Why don't you follow him on twitter.

2 Comments on "Extending Backbone.js constructors, the easy way"

  1. _kud says:

    Thanks buddy. Save my day. ;)

  2. I am regular reader, how are you everybody? This article posted at this web site is in fact pleasant.

    Look at my blog – news bloopers

Got something to say? Go for it!