Listening for events

One of the primary advantages of using the set and unset methods, as we just described, is that they allow other parts of your code to listen for changes to a Model's attributes. This works similar to listening for a DOM event in jQuery and is done using the on and off methods of the Model:

var book = new Backbone.Model({pages: 50});
book.on('change:pages', function() { // triggers when the "pages" of book  change
    alert('the number of pages changed!'),
});
book.set('pages', 51); // will alert "the number of pages has changed"
book.off('changes:pages'),
book.set('pages', 52); // will no longer alert

As you can see in the preceding code, the on method, just like jQuery's, takes two arguments: an event function and a callback function. When the event is triggered, Backbone invokes the callback function. The event listener can be removed using the off method. If you want your code to listen for multiple events, you can combine them with spaces, as shown here:

book.on('change destroy', function() {    // this callback will trigger after a change or a destroy
});

Backbone offers one significant improvement over jQuery however, in the form of an optional third context argument. If this argument is provided, the callback will be bound (as if you had used the _.bind method mentioned in the previous chapter) as it's registered:

var Author = Backbone.Model.extend({
    listenForDeathOfRival: function(rival) {
        rival.on('destroy', function celebrateRivalDeath() {
            alert('Hurray!  I, ' + this.get('name') + ', hated ' + 
                  rival.get('name') + '!'),
        }, this); // "this" is our "context" argument
    }
});
var keats = new Author({name: 'John Keats'),
var byron = new Author({name; 'Lord Byron'});
byron.listenForDeathOfRival(keats);
keats.destroy(); // will alert "Hurray!  I, Lord Byron, hated  John Keats!"

In the previous code, we define an Author class with a listenForDeathOfRival method, which takes a rival (another Author class) as an argument and sets up a listener for when the rival is destroyed. We pass the original author as the context argument, so when the callback resolves, its this method will be set to that author. We then call listenForDeathOfRival on byron and pass in keats so that byron listens for a destroy event on keats.

When we then trigger Keats' destruction in the final line, we trigger the event listener setup by listenForDeathOfRival, which gives the alert message. The message is able to include both the authors' names because when the callback resolves, Keats' name is available from the rival variable, while Byron's name is available as an attribute of the Model (because we passed his Model as the context argument when we set up the event listener).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.109.211