Click here to Skip to main content
15,513,648 members
Articles / Web Development / HTML
Article
Posted 23 Feb 2015

Stats

36.7K views
496 downloads
4 bookmarked

BackBone Tutorial – Part 8: Understanding Backbone.js Events

Rate me:
Please Sign up or sign in to vote.
4.96/5 (16 votes)
23 Feb 2015CPOL5 min read
In this article, we will look at events in Backbone.js.

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:

  1. BackBone Tutorial – Part 1: Introduction to Backbone.Js[^]
  2. BackBone Tutorial – Part 2: Understanding the basics of Backbone Models[^]
  3. BackBone Tutorial – Part 3: More about Backbone Models[^]
  4. BackBone Tutorial – Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service[^]
  5. BackBone Tutorial – Part 5: Understanding Backbone.js Collections[^]
  6. BackBone Tutorial – Part 6: Understanding Backbone.js Views[^]
  7. BackBone Tutorial – Part 7: Understanding Backbone.js Routes and History[^]
  8. 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.

JavaScript
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.

JavaScript
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.

JavaScript
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:

JavaScript
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.

JavaScript
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.

JavaScript
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.

JavaScript
book.off('something', ShowMeWhenSomethingHappens);

If we want to associate a callback with an event, that should only be called once, we can use once.

JavaScript
book.once('something', ShowMeWhenSomethingHappens);

And finally, how can we trigger an event? The events can be triggered by using the trigger function.

JavaScript
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.

JavaScript
var Catalog = Backbone.Model.extend({
    defaults: {
        ID: "",
        CatalogName: ""
    },

    // code omitted for brevity

    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:

JavaScript
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.

JavaScript
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.

JavaScript
catalog.stopListening(book);

If we want the equivalent of once in this scenario, we can use listenToOnce function instead.

JavaScript
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1220189813-Jun-17 5:15
Member 1220189813-Jun-17 5:15 
PraiseNice article to start with, really making concepts clear Pin
livinpresent_093-Nov-15 23:47
livinpresent_093-Nov-15 23:47 
GeneralNice tutorial Pin
Member 1198903519-Sep-15 2:29
Member 1198903519-Sep-15 2:29 
GeneralBrilliant &awesome & Great Pin
Ravikiran72p12-Sep-15 22:15
Ravikiran72p12-Sep-15 22:15 
QuestionBrilliant and easy to follow series Pin
mal clarke uk14-Jul-15 23:27
mal clarke uk14-Jul-15 23:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.