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