Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js: Backbone Events

In this article we will see another interesting part of backbone that will make your app actually does something: the Backbone Events.

Today we are going to learn about Backbone Events. Another interesting part of backbone that will make your app actually does something. Before we begin, let’s see the definition of events from the canonical backbone docs. Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Yep, you can bind your custom events using any desired name you choose. It is also stated that Events do not have to be declared before they are bound, and may take passed arguments. See Listing below.

Listing 1 : Backbone Events

var object = {};
_.extend(object, Backbone.Events);
object.on("alert", function(msg) {
  alert("Triggered " + msg);
});
object.trigger("alert", "an event");

So what’s going on here? Since this tutorial is aimed to the novice so I will try to make the explanation as detail as possible. First we declare an empty object, then we extend that object using underscore functionality _.extend(), remember we can use underscore’s power since backbone hard dependency is underscore. Extending object from Backbone.Events means copying all of Backbone.Events properties to the object, so now the object can use the properties and methods from the source object. If you are still unclear what I’m talking about let me give you the declarative syntax for extend, that is _.extend(destination object, source object).

In the next line, we bind an Alert event to object, by using object.on(). On() accept three arguments i.e events, callback, and optional context. In the listing above we only use the first two arguments. We provide Alert as event and a callback function containing a javascript alert to output the message whenever Alert event happens.

To simulate the actual event, we use object.trigger() that will trigger the event specified as the first argument, we can also pass optional arguments like in above example is “an event”. We can also use our custom events if necessary, to show you how it works let modify a few things from the listing 1.

Backbone.js

Figure 1: Backbone.js

Listing 2 : Custom Backbone Events

var object = {};
_.extend(object, Backbone.Events);
object.on("kick", function() {
  alert("Ouch, you just kick me");
});
object.trigger("kick"); 

It’s actually the same code and will do similar thing to Listing 1. The difference is, we have changed the ‘alert’ to our custom event name ‘kick’. So the object now will listen to kick event instead of alert. To trigger the kick event we simply use object.trigger(“kick”)

Great, so how do we use events in our Backbone Model and Collection? To better visualize what we can do later on our real app, we will continue our contrived scenario creating image gallery app from previous article Backbone.js: Getting deeper into model and Backbone Collection, if you haven’t read it, I suggest you to read it first. But if you know what you do, you may continue. To begin Let’s recall our Image model we have created.

Events on Model

Listing 3 : Backbone Model

var ImageModel = Backbone.Model.extend({
    defaults : {
        title : ‘untitled’,
        description : ’no description available’,
        owner : ‘anonymous’,
        date : ‘no date supplied’
}
});

To use Backbone.Events on our model, we will add some new line of codes to the existing model. like below.

Listing 4 : Event Handling on Model

var ImageModel = Backbone.Model.extend({
initialize: function(){
	this.on('change',this.someChange,this); //when some property in this object has changed, run this.someChange() function
},
defaults : {
        title : 'untitled',
        description : 'no description available',
        owner : 'anonymous',
        date : 'no date supplied'
},
someChange: function(model,options){
alert(‘something has changed’);
}
});
var photo = new ImageModel({title:’awesome image’});  //create new instance

photo.set(‘title’,’really awesome indeed’); //change the title attribute, this will trigger ‘change’ event

photo.set({title:’well i agree’},{agree: ‘yep’}); //alternative way to change model attribute with optional option passed, this will also trigger change event. </p>

Notice, in the listing 4 we add two new functions, they are ‘initialize’ function and ‘someChange’ function. initialize is a built-in function from backbone, it get’s called whenever new instance of class is created. Initialize function is a good place to put your event listener. Like in the listing 4 we put our listener to ‘change’ event on the object, and whenever ‘change’ occurs the this.someChange() callback is invoked. This callback is later defined in our Model which contain an alert to tell you that something has changed in this model. The ‘change’ event has two arguments ‘model’ and ‘options’ as you can see in the example, this means you can do something with these arguments. ‘model’ is the model that is changed, ‘options’ are optional arguments passed when the event triggered.

Okay, so our ImageModel will now listen to change events on itself, it will listen to any attribute change, but what if we only want to listen particular attribute change. We can do that by using colons after the events name followed by the attribute name, i.e ‘change:title’, this will only listen to change of title attribute and ignore the rest attribute change. Another example of events occur in the model are ‘destroy’, it is triggered when a model is destroyed, ‘save’ triggered when a model is saved to database or other persistence layer.

Events on Collection

We have covered the basic of events in our model, so now let’s move to play with collection. Actually we will be dealing with similar pattern like before. Let’s recall our collection from the previous article.

Listing 5 : Backbone Collection

//first create a model
    var ImageModel = Backbone.Model.extend({
        defaults: {
            title : ‘untitled’,
            description : ‘no description available’,
            owner: ‘Muhammad Azamuddin’,
            date: ’29 March 2013’
        }
});
 
//create  backbone collection
var GalleryCollection = Backbone.Collection.extend({
    model : ImageModel // tell the collection which Model to collect inside it.
});
//create a new gallery
var imageGallery = new GalleryCollection();
 

There are several built-in events may occur on our collection like when we add,remove,change a model, or when we fetch data from the server. To begin, we are going to listen add and change event from our collection. The code will look like this.

Listing 6 : Listening an add event on collection

//continue from collection in listing 5, we gonna add some new code
var GalleryCollection = Backbone.Collection.extend({
	model : ImageModel,
	initialize : function () {
		this.on(‘add’,this.newComer,this);
		this.on(‘change’,this.someChange,this);
},
newComer : function (model) {
	alert(‘welcome ’+ model.get(‘title’);
},
someChange: function(){
alert(‘model has changed’);
}
}); 
//create a new gallery
var imageGallery = new GalleryCollection();

//trigger the events

var pic = {title:’new awesome pic’}); 
imageGallery.add(pic); //this will trigger add event on our collection
pic.set(‘title’,’awesome and beautiful pic’); //will trigger change events on our collection

In Listing 6, we put the code to listen to events in the initialize functions just like when we did it in our model. The initialize function will get called each time a new collection instance is created. Notice we listen to add and change events from our collection, everytime the events occur respective callback will get invoked. The ‘add’ event will be triggered each time we add new model to our collection. The ‘change’ event will be triggered each time a model inside a collection has changed. But wait, the model change, should the change event only available to the model? the answer is the change event will buble up from model to collection, so we can convenienly listen to model’s change from our collection.

Silence The Event

If you'd like to prevent the event from being triggered, you may pass {silent: true} as an option. Note that this is rarely, perhaps even never, a good idea. Passing through a specific flag in the options for your event callback to look at, and choose to ignore, will usually work out better.

Listening to Other Object’s event

Another handy listener is listenTo(), accept three arguments that is other object, event, callback. The advantage of using this form, instead of other.on(event, callback), is that listenTo allows the object to keep track of the events, and they can be removed all at once later on. Sometimes, you will need to a model’s event from your view, listenTo is useful for that. See the listing below.

Listing 7: Listening to other object’s event

//if you put this code inside a view, the view will now listening to its model change event
this.listenTo(this.model, ‘change’, this.doChange);

Okay, that’s all we learn a very basic usage of backbone events, you can read the full reference of backbone event on the official documentation. Please note, this article is based on backbone version 1.0.0, See you next time.



A passionate and visionary web developer who falls in love with web technologies. Always excited to learn more, just like you.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login