Friday 2 January 2015

jQuery events - direct and delegated events

Historically Jack bound many events to buttons, forms, links and text boxes since he started working with jQuery. He has even played with event propagation and fixed some curious issues by using stopPropagation() method. But this is for the first time that an event he bound to a simple link just didn't work. There were no silly syntax errors.
See the code snippet that Jack wrote.
$(".sub-heading").click(function() {
    $(this).css({"background-color": "yellow"});
});

Turning point
Jim has committed code which loaded some html content with the same "sub-heading" class via AJAX. Highlighting on click was not working for only those subheadings.
Jack felt a little relaxed, but dwelling more he understood that Jim is not the culprit! Jim has correctly loaded the content which had the elements with the same class name "sub-heading" via AJAX. Something related to events was not working as expected for the dynamically loaded content.

Event revelations

The facts Jack learnt regarding JQuery events has totally changed the way he approached events in jQuery.

There are two types of jQuery events
  1. Direct or directly bound events
  2. Delegated events

1. Direct or directly bound events

The event Jack created was indeed a direct event. The known fact regarding these events before was that "it works usually..".
Following are the other facts revealed.
- Every element matching the selector has a copy of the handler and it is triggered upon the event.
- The event is propagated till the document up in the hierarchy, for those elements having a matching the selector as bound in the event.
- If the event binding is done on document ready, only those elements matching the selector present when document is ready will be bound. Those elements created dynamically won't be bound.

Jack's Fixing instinct

Jack understood the issue. The first idea that hit his mind was to attach the handler as soon as Jim dynamically loaded the content. He even searched for the success handler of Jim's AJAX call. But, he was just curious about the other type of jQuery event and thought to peep into that as well.

2. Delegated events

Learning delegated events, Jack was surprised to knowing that it was the most suitable one for the situation. Here is why.
  • It is bound to a container having the the target elements that should respond to the event.
  • One and only one handler is shared by all the the target elements.
  • It works for future elements or elements that are dynamically loaded.
  • The event is propagated and triggered for elements with matching selector found from the inner most element to those up in hierarchy in the container. Otherwise it won't be fired for matching elements not inside the bound container.
This is how Jack refactored his code after observing that all the present and future subheadings are loaded into the "div#container"
$("#container").on("click", ".sub-heading", function() {
    $(this).css({"background-color": "yellow"});
});

The on handler

Earlier JQuery used live, bind, delegate etc for dealing with different event handling usecases. As of JQuery 1.7 the "on" handler includes all those scenarios and these methods are deprecated. Here is the basic syntax.

$("{container}").on("{event}", "{selector}", function() {
    
});

"on" method can be used to attach delegated events. But it can also be used to attach direct events. Omitting the "selector" argument or specifying it as null, the handler is bound directly. See below.

$(".sub-heading").on("click", function() {
    $(this).css({"background-color": "yellow"});
});

If there are events bound to a set of elements, delegated event is the way to go. Suppose there is an html table with one thousands rows, isn't it smart to bind the event to the table than to each of the thousand rows?

Doing it once using one

Jack also learnt that he can use "one" instead of on to trigger event only once for the matched selector.

Switching it off

The events attached using "on" can be removed using "off".
• • •

1 comment:

  1. Harrah's Cherokee Casino Resort - Mapyro
    Harrah's Cherokee 보령 출장샵 Casino Resort is a Native American 동두천 출장샵 casino 천안 출장샵 in Cherokee, North Carolina. Find reviews, ratings, latest 화성 출장안마 pictures and text of  Rating: 2.5 나주 출장샵 · ‎21 reviews

    ReplyDelete

Drop your comment here