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.

4 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

  3. Normally I do not learn article on blogs, but I wish to say that this write-up
    very pressured me to try and do so! Your writing style has
    been amazed me. Thank you, quite great article.

  4. Aw, this was a very good post. Taking the time and actual effort to create a very good article… but what can I say… I
    put things off a lot and don’t manage to get anything done.

Got something to say? Go for it!