Listening with Backbone helps your Memory
Backbone 0.9.9 was released today! With it came the inclusion of a long-time requested feature to help views manage the binding and garbage collection of the events bound to the objects within the view. The new methods that I'm going on about are:
- listenTo(object, events, callback): Takes the same arguments as Backbone's Event.on with the addition of having the view remember which object is bound to which events and callbacks to unbind them later on.
- stopListening(object, events, callback): Calling it by yourself with the original object, events and callback will remove it from the registry, and it gets called for you during remove with no arguments to unbind all events for the view.
This is big news for folks developing single page applications. Especially where you are building up and tearing down many views without page reloads. If you're not careful about managing object event listeners, you end up with many detached objects that will never get garbage collected. The outcome is that your application continues to grow in memory usage, and performance degrades rapidly as time goes on.
Taking it Further
Being able to listenTo events on objects is great, but we can take it an additional step in the right direction. One of my favourite parts of Backbone is how declarative you can keep your view classes. This makes it immediately obvious what a view is responsible for and what it's connected to just by reading the first few ...