Part 8: Understanding Backbone.js Events

阅读更多
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 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:

  • Part 1: Introduction to Backbone.Js
  • Part 2: Understanding the basics of Backbone Models
  • Part 3: More about Backbone Models
  • Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
  • Part 5: Understanding Backbone.js Collections
  • Part 6: Understanding Backbone.js Views
  • Part 7: Understanding Backbone.js Routes and History
  • 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 let 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 onto hook the callback functions with the event. Lets 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 triggeron the event name. Lets invoke the function and see the results.

testObj.trigger('something', 'Hello events');


Part 8: Understanding Backbone.js Events_第1张图片

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 lets say of we have a simple model like following.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    }
});

It if already hooked with the backbone events. So if 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');


Part 8: Understanding Backbone.js Events_第2张图片

In the same way events can be used with any of the backbone object 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. onattaches a callback function with an event.

var book = new Book();
book.on('something', ShowMeWhenSomethingHappens);

The callback functions that are attached to an event using onfunction 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 offfunction.

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

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 lets try to understand this scenario better. Lets say I have another model Catalogin my application.

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

    // code ommitted for brevity

    bookChanged : function(book) {
        alert(book.get("BookName"));
    }
});

What this model is expecting is that whenever a book is changed, the bookChangedfunction 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 listenTofunction. Lets 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);


Part 8: Understanding Backbone.js Events_第3张图片

In the above code, we are still subscribing the catalog object with the book’s event but using listenTofunction on the catalog object instead. If we want to remove the associated object the we can use the stopListeningfunction.

catalog.stopListening(book);

If we want the equivalnt of once in this scenario, we can use listenToOncefunction 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 the 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 build 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.

原文链接: http://rahulrajatsingh.com/2015/02/backbone-tutorial-part-8-understanding-backbone-js-events/
  • backboneSample.zip (126.9 KB)
  • 下载次数: 0

你可能感兴趣的:(backbone,javascript,mvc)