Joao Carlos

Automatic binding of this in Backbone.js

Having to bind the value of this manually in Backbone.js is not only tedious but can also result in frustration after forgetting to add a function name to the list.

And that's why many people extend Backbone.js with a autoBind function that automatically binds all functions. However, if you always want the auto bind functionality, why not take it a step further and have this behavior by default?

Over at TenFarms we create our own View, Model and Collection classes that extend from Backbone's implementations. I like to think of Backbone.js as a meta-framework we extend with further functionality we need and prefer extending Backbone under our own namespace.

Our View implementation with automatic binding is very simple:

TenFarms.View = Backbone.View.extend({
  constructor: function() {
    var functions = _.difference(_.functions(this), 
_.functions(TenFarms.View.prototype));
    _.bindAll.apply(_, [this, "render"].concat(functions));
    Backbone.View.prototype.constructor.apply(this, arguments);
  }
});

Our code doesn't actually look like that since our recent switch to CoffeeScript. It's pretty much the same but we can take advantage of the super call:

class TenFarms.View extends Backbone.View
  constructor: ->
    functions = _.difference _.functions(this), 
_.functions(TenFarms.View.prototype)
    _.bindAll.apply _, [this, "render"].concat(functions)
    super

The implementation is very straightforward: use Underscore.js functions to determine which functions our view has, and remove all functions defined by Backbone.View from that list so we don't interfere with the any Backbone code. Then we call bindAll just like we would when initializing a View. Notice that we have to manually add render in there because it's actually a noop function defined in Backbone.View.

And that's it. You can now do the same for your Model and Collection if you want the same functionality there.

This article was originally posted on the TenFarms development blog, but is here also for reference.

This article was posted on 2012-05-17. Like it? Share it.


Joao Carlos, that's me!

Meet the author:

Hi, I'm Joao Carlos, an iOS and Ruby developer currently living with my wife in Helsinki, Finland. I can make some pretty neat apps and I write about what I learn on the way. More about me »