Coccyx: plug up those backbone leaks

June 14, 2012 Onsi Fakhouri

A number of projects at Pivotal have been using Backbone.js to build single page web apps. I’ve enjoyed using Backbone: it’s lightweight, unopinionated, helps encourage good separation of concerns between models and views, and reduces a fair bit of JavaScript boilerplate by bringing just enough framework to the table.

Unfortunately, it’s very easy to write Backbone code that leaks – especially in the view layer. A common backbone pattern is to set up some event bindings for a view:

var MyView = Backbone.View.extend({
    initialize: function() {
        this.model.on('change', this.update, this);
        this.someOtherModel.on('change', this.update, this);
        this.boundResizeHandler = _.bind(this.resizeHandler, this);
        $(window).on('resize', this.boundResizeHandler);
    },
    ...etc..
});

If your app needs to switch between several such views it is not enough to simply remove the view’s DOM and null out any references to the view. You must also unbind these event bindings in order for the view to be garbage collected. Moreover, if this view contains any subviews, you must also tear down all event bindings for all its subviews. If you do not succesfully clear out all bindings the view (and/or its subviews) will leak.

What’s worse: while there are some great tools out there to identify leaking objects, Backbone’s default constructor lists all objects as type child. This makes finding the leaky Backbone objects that are instances of MyView nearly impossible in Chrome’s heap propfiler.

Coccyx attempts to adress these problems by doing two things:

  1. Coccyx adds named constructors to Backbone. You no longer need to wonder which child is yours. By adding constructorName when you extend a Backbone class you’ll be able to easily tell which object is which in the console and the heap profiler.

  2. Coccyx implements teardown-able view hierarchies. You can easily build view hierarchies in which parents are aware of their children and can tear the entire structure down by calling tearDown() on a root node. tearDown() automatically unbinds any Backbone event bindings, cleans up DOM events and gives your view a chance to perform any custom teardown via a callback.

There are many more details at https://github.com/onsi/coccyx. Bug reports and pull requests are encouraged!

About the Author

Onsi Fakhouri

Onsi Fakhouri is the Senior Vice President, Cloud R&D of Pivotal.

Previous
PivotalBooster gets a boost
PivotalBooster gets a boost

We're always thrilled to see people build cool things with our API, but we're even more excited when these...

Next
git add -e
git add -e

git add -e is like git add -p, except instead of adding things at the hunk level, you edit the entire patch...