documentcloud/backbone — pull request #1363 by kevinrobinson (2012-05-31 18:20:48+00:00)
Title: Adding View#bindTo, #unbindFromAll and #destroy for tracking bindings to external objects

Inspired by all the people presenting at BackboneConf who have rolled their own version of this to manage cleaning up bindings when destroying Views. This is what we use on a project I work on, but if other people have better flavors or takes on this, I'd happily adopt those if they made it into core.

This pull request adds a bindTo method to Backbone.View that can be used as an alternative to:

model.bind('change', callback, view);

The proposed usage is:

view.bindTo(model, 'change', callback);

The bindTo method does the binding but also tracks the View's bindings to external objects in this._bindings, so that they can later be removed when the View is ready to be destroyed. This is done in #unbindFromAll, and the #destroy method simply calls #unbindFromAll at this point.

I tried adding tests as well, but they aren't as cleaned up as they could be. I've only ever written Jasmine tests so I welcome any restructuring or feedback here.

Thanks!