JQuery Event Handlers - What's the "Best" method
What's the difference between the following ways of attaching an event handler in JQuery?
(function () {
var $body = $("body");
$('button').click(function () {
console.log(this) + " - 1";
});
$('button').on('click', function () {
console.log(this) + " - 2";
});
$(document).on('click', 'button', function () {
console.log(this) + " - 3";
});
$body.on('click', 'button', function () {
console.log(this) + " - 4";
});
$body.find('button').on('click', function () {
console.log(this) + " - 5";
});
})();
I have found some cases where one seems to work and the other does not. For example Handler 2 below, does not work while Handler 1 does. In order to make this work I had to implement Handler 3 which is obviously less efficient.
$retrieveCust = $("#bxRetrieveCustomer");
// Handler 1
$retrieveCust.find(".icoX").on("click", function () {
// DO SOMETHING
});
// Handler 2
$retrieveCust.find(".tag-open").on("click", function () {
// DO SOMETHING
});
// Handler 3
$(document).on("click", ".tag-open", function (event) {
// DO SOMETHING
});
Here's the HTML
<div class="box" id="bxRetrieveCustomer">
<h1>RETREIVE CUSTOMER</h1>
<div class="icoX">X</div>
<div class="box-liner10">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Email</th>
<th>password</th>
<th></th>
</tr>
<!-- ko foreach: Customers -->
<tr>
<td data-bind="text: FirstName"></td>
<td data-bind="text: LastName"></td>
<td data-bind="text: DateOfBirth"></td>
<td data-bind="text: Email"></td>
<td data-bind="text: Pwd"></td>
<td><a class="tag-open"></a></td>
</tr>
<!-- /ko -->
</table>
</div>
</div>
My guess is that you're seeing a difference in behavior because some objects in your page are being dynamically added/removed and you need delegated event handling in order to automatically have events for newly added objects.
Among your various examples, there are two basic types of behaviors here:
Behavior #1: Static Event Binding
$('button').click(function () {
console.log(this) + " - 1";
});
$('button').on('click', function () {
console.log(this) + " - 2";
});
$body.find('button').on('click', function () {
console.log(this) + " - 5";
});
The above three all attach a click handler directly to each button object that exists in the page at the time the code is first run. These are basically identical. The .click()
syntax is just a shortcut. The $body.find('button')
is functionally equivalent to $('button')
since both select all buttons in the body.
Note: these event handlers will only be attached to the button objects that exist when this code is first run. Any button objects that are subsequently added to the document will not have an event handler attached to them.
Behavior #2: Dynamic or Delegated Event Binding
$(document).on('click', 'button', function () {
console.log(this) + " - 3";
});
$(document.body).on('click', 'button', function () {
console.log(this) + " - 4";
});
These two use delegated event handling to watch for clicks that bubble up to the document or body objects. These are likewise similar. These will handle any click event that originated on a button tag. Since the event handler is not attached directly to the button object, buttons can come and go in the page and all button objects that exist at any time will get this handler behavior.
It is generally NOT recommended to bind delegated methods bound to the document
or body
objects. In fact, this is why .live()
has been deprecated because that's what it did and it can cause performance issues. The issue is that if you get lots of delegated events all bound to the same object, then every time an event occurs and it bubbles up to this object, jQuery has to compare the originating selector to a lot of different selectors to see which handler to call.
It is much better to bind delegated events to a parent object that is as close to the actual target objects as possible, but obviously you must pick a parent object that won't be added/removed (you need one that is constantly in the page).
In your more specific code example, assuming the bxRetrieveCustomer
div is not created dynamically, you should change this:
$(document).on("click", ".tag-open", function (event) {
// DO SOMETHING
});
to this:
$("#bxRetrieveCustomer").on("click", ".tag-open", function (event) {
// DO SOMETHING
});
Which will still be delegated event handling, but will bind the event handler much closer to the actual object so it will work more efficiently.
Efficiency
As for which is best, it depends:
If you have objects that are created after you run the event binding code that you want events bound to, then you will want to use delegated event handling on the closest ancestor object that is not dynamically created after-the-fact.
If you have a very large number of objects (even if they are static), then delegated event handling will install much more efficiently because it installs one event handler for all of them rather than thousands for each individual object.
If you have a medium or small number of static objects, then binding event handlers directly to them is the most efficient. It will take a tiny bit more time to initially bind an event handler to each object, but then be the most efficient at the time of the event.