I was investigating a bug and decided to review the jQuery.on()
docs to make sure I understood delegated events. I was surprised to read:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
I was surprised because I'd been binding events to elements not in the DOM, and upon inserting the elements into the DOM, those elements would respond to events that bubbled through!
I was so confused by this statement that even tested my understand of it. You can find this test here: http://jsfiddle.net/eUuv4/.
In summary, I make a Backbone View:
var View = Backbone.View.extend({
template: _.template('<div class="inner"><button>Say hello</button></div>'),
initialize: function (options) {
this.name = options.name;
this.$el.append($(this.template()));
},
events: {
'click button': function () {
console.log('Hello from ' + this.name);
}
},
});
And then construct it with two different elements: one that is in the DOM; and one that is not in the DOM when the view is constructed. Upon inserting the second variant into the DOM, as I expected, its element responds to delegated events that pass through it.
So, what are the jQuery docs trying to say with the above quoted statement?