Posted on by & filed under Programming & Development, Tutorials.

Backbone.js is a client-side MV* framework that provides a simple, but powerful, events API. All Backbone objects (Models, Collections, Views & Routers) trigger events and can listen to events. This architecture is an implementation of the Observer design pattern and using events makes it easier to keep the various parts of your application loosely coupled.

In this post we’ll look at how to set a handler to listen to all of the events on a Backbone object, and why this is useful. Backbone has two main methods for setting up event handlers: .on and .listenTo. For the examples in this post, we’ll be using the .on method. This method works in similar ways to other event libraries, such as jQuery or NodeJS’s EventEmitter.

The .listenTo method was added to Backbone in version 0.9.9 and it is a useful tool to prevent memory leaks. It’s primarily used when a short-lived object needs to observe events in a long-lived object. An example would be if a view needs to listen to changes on a model. The view may be destroyed and created multiple times in the course of running the application, but the model is likely to only be instantiated once – when the application is initialized.

There is a whole catalog of events that are triggered internally by Backbone. It is also possible to trigger and listen to custom events. A useful feature of Backbone Collections is that any event triggered on a model within that collection will also be triggered on the collection itself. For example:

In the above code, you can see that when we changed an attribute on the ruby model, the change event was triggered on the collection. This also works with custom events:

So any event that is triggered on a model, whether a built-in Backbone event or a custom event, will be triggered on the collection that the model belongs to. Let’s dive into Backbone’s source to see how this is implemented:

When a Model is added to a Backbone Collection, a handler is added to the special “all” event. For instance, the _onModelEvent handler needs to perform custom logic for some events:

  • add and remove events are stopped from being re-triggered, since they are usually initiated by the collection.
  • destroy events on the model cause the model to be removed from the collection.
  • change events to the models idAttribute cause the collection to adjust its internal _byId lookup hash.
  • All events, except for add and remove, are re-triggered on the collection.

The Backbone source is well commented and very readable. To see how the events system sets up listeners for the “all” event look at the Backbone Events section.

Now that you’ve seen how the “all” event is used internally by Backbone, let’s see how it can be used in your own application. While plugin authors may use .on(“all”,…”) to implement advanced functionality, most of the time I use this feature for debugging. In a complex Backbone application, multiple events are fired by models and collections, and it can help to log them all to the console. To illustrate how this can be useful, let’s add some all listeners to Hubbub, an example Backbone application, to manage some Github issues. Navigate to the application, open up the console, and enter the following code:

Now try adding a repo to your board and moving issues around. You will see a steady stream of events being logged to the console. The order of these events can be really useful in debugging an application. For example, if you see unexpected change events on your models after sync events, then you may need to check that the responses from your server are as you expect.

We’ve only touched the surface of what can be done with Backbone Events. The “all” event is incredibly useful for debugging in Backbone, and it would be great if Node’s EventEmitter had the same feature.

For more details about Backbone.js, see the ebooks referenced below.

Safari Books Online has the content you need

While there are many frameworks that seem to be faster to get started with, Backbone’s lack of surprises, clear documentation, speed and flexibility make it a good fit for all types of applications. Developing a Backbone.js Edge incorporates the best practices and techniques from the combined authors’ experience of developing many Backbone applications. Some of the resources on the web advocate inefficient or inelegant solutions and there are few that cover the whole library. In this book we aim to provide a complete guide to Backbone and equip you to start using the library straight away.
If you’re looking to use the single-page application model to build your site’s frontend, Backbone.js is an ideal framework for the job. Developing Backbone.js Applications provides all of the information you need to create structured JavaScript applications using Backbone.js and its unique flavor of the model-view-controller (MVC) architecture.
The enthusiasm behind Node doesn’t just reflect the promise of server-side JavaScript. Developers also have the potential to create elegant applications with this open source framework that are much easier to maintain. Follow author Mike Wilson as he builds a social network application oriented toward real-time updates. Building Node Applications with MongoDB and Backbone shows you how to build complete applications that combine the strengths of Node, the MongoDB scalable storage solution, and the Backbone toolkit for clean application design in the browser.

About the author

Dave Tonge is a Backbone.js contributor and web developer at Simple Creativity. He is a co-author of Developing a Backbone.js Edge, and can be reached at: github.com/davidgtonge.

Tags: .on method, Backbone collections, Backbone.js, events, Github, MV* framework, Observer design pattern,

Comments are closed.