Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Event Handlers - What's the "Best" method

Tags:

jquery

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>
like image 882
Gary O. Stenstrom Avatar asked Mar 16 '12 00:03

Gary O. Stenstrom


People also ask

Which method is used to attach a handler to an event?

9) Which of the following jQuery method is used to attach a handler to an event? Explanation: The jQuery bind () event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs.

How to remove all event handlers from an HTML element?

To remove all event handlers mean to have the plain HTML structure without all the event handlers attached to the element and its child nodes. To do this, jQuery's clone () helped.

Is it possible to attach event handlers to a jQuery event?

"As of jQuery 1.7, the .live () method is deprecated. Use .on () to attach event handlers. Users of older versions of jQuery should use .delegate () in preference to .live ()." api.jquery.com/live Ah, fickle jQuery, one day you bring 300 rep to a guy, the next day it's obsolete. This can be done by using the unbind function.

How to add multiple event handlers to the same object?

Ah, fickle jQuery, one day you bring 300 rep to a guy, the next day it's obsolete. This can be done by using the unbind function. You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones. There are several strategies for changing event handlers, such as event namespaces.


1 Answers

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.

like image 174
jfriend00 Avatar answered Sep 21 '22 09:09

jfriend00