Introduction
In this article, we will look at events in Backbone.js. We will see how backbone provides us events and how we can use backbone events in our application.
Background
Events are a vital part of any application framework. Events are useful mainly in two scenarios when it comes to applications. Events can be particularly very useful when we want to implement a publisher subscriber model in our application where any change in one area of the application (the publisher) will trigger a notification to everyone who is interested (subscribers).
There are a plethora of JavaScript libraries that can be used to implement eventing in our JavaScript application. Backbone also provides a very nice implementation of eventing mechanism which makes the use of publisher subscriber model in our application seamless. Let us now look at how we can use events in a backbone application.
Link to complete series:
- BackBone Tutorial – Part 1: Introduction to Backbone.Js[^]
- BackBone Tutorial – Part 2: Understanding the basics of Backbone Models[^]
- BackBone Tutorial – Part 3: More about Backbone Models[^]
- BackBone Tutorial – Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service[^]
- BackBone Tutorial – Part 5: Understanding Backbone.js Collections[^]
- BackBone Tutorial – Part 6: Understanding Backbone.js Views[^]
- BackBone Tutorial – Part 7: Understanding Backbone.js Routes and History[^]
- BackBone Tutorial – Part 8: Understanding Backbone.js Events[^]
Using the Code
Backbone provides a very simple, clean and elegant way to use events. What backbone does is that it lets any object to be associated with backbone events simply by extending from the Backbone.Events.
This can be done by calling _.extend
method on the object instance. Let us create a simple object that extends from Backbone.Event
.
var testObj = {};
_.extend(testObj, Backbone.Events);
Once we have extended from Backbone.Event
, we can use on
to hook the callback functions with the event. Let's define a simple function and subscribe to an event.
function ShowMeWhenSomethingHappens(message) {
alert(message);
}
testObj.on('something', ShowMeWhenSomethingHappens);
Now the simplest way to invoke this event is by calling the trigger
on the event name. Let's invoke the function and see the results.
testObj.trigger('something', 'Hello events');
So we can see how simple it is to use triggers with backbone. Or is it? The only pain point I see in this event mechanism is the hookup of Backbone events with objects using _.extend
. Fortunately, we don't have to call this extend to hook backbone eventing mechanism with any object. If we have an object that extends from a backbone type, i.e., model, view, collection, then we have the event mechanism hooked with it by default. So let's say if we have a simple model like the following:
var Book = Backbone.Model.extend({
defaults: {
ID: "",
BookName: ""
}
});
It is already hooked with the backbone events. So if I run the following code, it should just work fine and show us the alert like the previous code.
var book = new Book();
book.on('something', ShowMeWhenSomethingHappens);
book.trigger('something', 'Hello events - backbone model');
In the same way, events can be used with any of the backbone objects seamlessly. Let us now look at the functions that can be used to take full control over these events. The first function that is of interest to us is on
. on
attaches a callback function with an event.
var book = new Book();
book.on('something', ShowMeWhenSomethingHappens);
The callback functions that are attached to an event using on
function can be removed by using off
. So if we want to remove the callback function attached to the event in the previous step, we just have to use the off
function.
book.off('something', ShowMeWhenSomethingHappens);
If we want to associate a callback with an event, that should only be called once, we can use once
.
book.once('something', ShowMeWhenSomethingHappens);
And finally, how can we trigger an event? The events can be triggered by using the trigger
function.
book.trigger('something', 'Hello events - backbone model');
These are the basic functions that we can use to subscribe to events. The important thing to note here is that these functions are being used on the object that is publishing the events. What if we want to use another object, i.e., the subscriber, then there is another set of functions that we can use. Before looking at the function, let's try to understand this scenario better. Let's say I have another model Catalog
in my application.
var Catalog = Backbone.Model.extend({
defaults: {
ID: "",
CatalogName: ""
},
bookChanged : function(book) {
alert(book.get("BookName"));
}
});
What this model is expecting is that whenever a book is changed, the bookChanged
function will get called. One way to do that is by using the on
function as:
var catalog = new Catalog();
var book = new Book({BookName : "test book1"});
book.on('changed', catalog.bookChanged);
book.trigger('changed', book);
Another way to perform the same thing is by using the event association functions on the subscriber, i.e., the catalog
object. To achieve this, we need to use the listenTo
function. Let's see how this can be done.
var catalog = new Catalog();
var book = new Book({BookName : "test book1"});
catalog.listenTo(book, 'changed', catalog.bookChanged);
book.trigger('changed', book);
In the above code, we are still subscribing the catalog
object with the book
's event but using listenTo
function on the catalog
object instead. If we want to remove the associated object, then we can use the stopListening
function.
catalog.stopListening(book);
If we want the equivalent of once in this scenario, we can use listenToOnce
function instead.
catalog.listenToOnce(book, 'changed', catalog.bookChanged);
The benefit of using these set of functions over the previously shown one is that the subscribers can keep track of all the events they are subscribed to and then selectively add and remove their subscriptions.
Note: The above code example is very contrived and far from the real world example. Its only purpose is to show how the given set of functions work.
There are a lot of built in events that backbone framework triggers that we can subscribe to in our application. For example "change
" will be triggered on a model when its state is changed. "add
" and "remove
" will be called whenever an item is added or removed from the collection respectively. There are a lot of such built in events that the framework triggers on models, view, collections and routes. I recommend referring the backbone documentation for the exhaustive list.
Point of Interest
In this small article, we looked at events in backbone. How backbone makes it extremely easy to work with events and how it provides a lot of built in events that can readily be subscribed from the application. This article has been written from a beginner's perspective. I hope this has been informative.
History
- 24th Feb, 2015: First version