Saturday, October 13, 2012

JQuery Events- Understand the insight - 2

JQuery provides different methods to attach an event to any element. All those method does the same thing but are different in some aspects like how the event get attached to an element and how does it get fired once an actions take place.
Lets try to understand all the methods provided by JQuery and see how do they differ from each other.

Here is the Html code we will use for all the jquery examples -
<div id="root">
    <div id="child1">
        <p>Hi this is para.</p>
    </div>
    <div id="child2">
        <p id="child2Para">This is another paragraph.</p>
    </div>
    <div class="EmptyDiv">
        Empty Div
    </div>
</div>

Bind() - Attach a handler to an event for the elements. When we use Bind method, the JQuery traverse the whole DOM tree and check if the selector matches, then attach the event with the element. When the action happens(click), the event get fired from the element directly, and bubbles up. 
We can attach multiple events also. Here is the example -
 $(document).ready(function(){
    $("#child2").bind('click',function(){
        alert('child 2 clicked');
    });
});
If we click on child2, then it will alert "child 2 clicked". Following example shows how to attach multiple events -
$(document).ready(function(){
    $("#child2").bind({'click':function(){
        alert('child 2 clicked');
    }, mouseenter: function() {
        alert('Mouse enter to child2');
    }});
});
If there are multiple events that need to be fired on same action, then they will be fired in the sequence of subscription.
Drawback- In this case the subscription can be little expensive for large DOM structure, as the Jquery traverse the whole DOM tree and attaches the event to the element. 

live() - Attach an event handler for all elements which match the current selector, now and in the future.
In case of Bind the handler get attached to the element itself, but in case of live the handler get attached to the document object.
Here is example which demonstrate the behavior -
$(document).ready(function(){
    $("p").live({'click':function(){
        alert('paragraph clicked');
        $(this).after("New Paragraph
");
    }});
});
In the above code if you click on paragraph it will append new paragraph in the page. The new paragraph will also have this event attached. If you replace the live with bind in above code you wont find the event attached with the newly create paragraphs.
Drawback- live() method is no longer recommended.  Because it have performance and chaining related issues. As the live event get attached to document object by default(because no context is mentioned), thus once we click on any element, then the javascript will traverse whole DOM tree to find that element and execute the handler

delegate()- Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. It is very much similar to the live() function, except in this case the event get attached to the element(like Bind()) not with the document object.  So the performance hit we get in case of live() wont be applicable in this case.
The above code can be re-written using delegate in the following way -
$(document).ready(function(){
    $("body").delegate("p",{'click':function(){
        alert('paragraph clicked');  
        $(this).after("New Paragraph
");    
    }});
    $("body").delegate("div",{'click': function(){
        alert('div clicked');
    }});
});
Drawback - The drawbacks are very much similar to the one mentioned in Bind, that is if the DOM tree is big then while subscription we might face some performance hit.


On() - Attach an event handler function for one or more events to the selected elements.
It is the combination of delegate and Bind and most recommended event subscription method provided by Jquery. If we pass the selector in the on function then it behave like delegate, and if we skip it, it works like Bind() method. Here are the example -
$(document).ready(function(){
    $("body").on("click", "p", function(){
        alert('paragraph clicked');
        $(this).after("New Paragraph
");
    });
});
Above code works similar to the delegate, and if we remove the "p" as second parameter it will behave like Bind().

Stop Bubbling of Event-
you can return false from the event handler to stop its propogation to the parent elements. Once we do it, it internally calls event.stopPropogation().

No comments:

Post a Comment