15 December 2012 0 Comments
4 Changes in Backbone.Events you should know about

I really liked the latest update of Backbone to version 0.9.9 which will probably be the last one before 1.0.

There are a lot of changes and tweaks, but what I really like are the changes/additions made to the Backbone.Events.

1. Global Notifications

Backbone now supports a global Pub/Sub notification system. The implementation is very similar to what I’ve suggest at a previous blog post (Backbone global notifications).

The Backbone object now extends Backbone.Events instead of adding another object onto it. Smart and simple.

2. Defeat memory leaks

If you’re new to Backbone then you probably don’t even know about the problem of memory leaks when binding to objects.

If you’ve been using Backbone for a project or two, you already know that for each .on you call on an object, you must also call .off in order to let the Garbage collector do its job. We always seem to forget this especially when Views are binding to Models.

Backbone now allows you to bind the other way around. A view can bind to a few model notifications and then unbind from all of them with a single call.

This is done with the view.listenTo(model, ‘event-name’, func) anview.stopListening(). The default remove() function of views will call stopListening() for you so you won’t forget.

3. Bind only once

Another cool new feature is binding to a notification only once. A call to once() ensures that the callback only fire once when a notification arrives.

4. Alternative syntax

Binding now supports a map syntax:


    ‘change:name’ : this.nameChanged,

    ‘change:age’ : this.timeMachine,

    ‘change:height’ : this.newShoes


This is much cleaner than having three separate calls to .on and aligns well with the events hash used for Views.

Happy coding!

← Read More