Handling events

While the Views we've described so far are great for creating and/or wrapping existing HTML elements, they're not very good at responding when a user interacts with them. One approach to solve this problem will be to hook up event handlers inside a View's initialize method, as follows:

var FormView = Backbone.View.extend({
    id: 'clickableForm',
    initialize: function() {
        this.$el.on('click', _.bind(this.handleClick, this));
    },
    handleClick: function() {
        alert('You clicked on ' + this.id + '!'),
    }
});
var $form = new FormView().$el;
$form.click(); // alerts "You clicked on clickableForm!"

However, there are two problems with this approach, as follows:

  • It's not terribly readable
  • We have to bind the event handler when we create it so that we can still reference this from inside it

Luckily, Backbone offers a better way, in the form of an optional property called events. We can use this events property to simplify our previous example:

var FormView = Backbone.View.extend({
    events: {'click': 'handleClick'},
    id: 'clickableForm',

    handleClick: function() {
        alert('You clicked on ' + this.id + '!'),
    }
});
var $form = new FormView().$el;
$form.click(); // alerts "You clicked on clickableForm!"

As you can see, using the events property saves us from even having to write an initialize method at all, while at the same time, it also takes care of binding the handleClick event handler to the View itself. In addition, by defining the event handlers in this way, we let Backbone know about them so that it can manage to remove or rebind them as needed.

When you instantiate a View, Backbone calls a delegateEvents method, which checks the events property, binds all the handlers found in it, and then creates listeners for the appropriate events using jQuery. There is also a corresponding undelegateEvents method, which can be used to remove all the event handlers. Normally, you won't need to call either of these methods yourself because Backbone will call them for you.

However, if you change a View's el element without telling Backbone (for example, yourView.el = $('#foo')[0]), Backbone won't know that it needs to hook up the events to the new element, and you will have to call delegateEvents yourself.

Alternatively, instead of changing a View's el element manually and then calling delegateEvents afterwards, you can use a View's setElement method to do both at the same time, as follows:

var formView = new Backbone.View({el: '#someForm'});
formView.setElement($('#someOtherForm'));
// formView.el == someOtherForm
..................Content has been hidden....................

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