2
votes

I'm trying to understand exactly when and how jQuery events bind in a Backbone.View. If I have a view:

var MyView = Backbone.View.extend({ events: {"click" : "handler"} });

Will backbone bind the click event on calling render()? On appending body? Something else?

1

1 Answers

2
votes

Event handlers are bound after calling initialize. Here's the source code, note the delegateEvents method:

var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this._configure(options || {});
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
};

The delegateEvents method then has jQuery code like this:

this.$el.on(eventName, selector, method);

A specific example, listening to click events on the view element and delegating clicks on a button with a load-more class to a handler:

this.$el.on("click", ".load-more", function(){});