Tuesday, 17 July 2012

Jquery Delegate vs Bind

With jQuery 1.4.2 launch, a new method called "delegate()" was introduced. This method attaches a handler to one or more events for selected/specified elements. Let's take an example. I have created a table and using delegate method, I will attach the click event handler to every td element.
<table border="1" width="200px" cellspacing="5" cellpadding="5">
   <tr>
       <td>Item 1</td>
       <td>Item 2</td>
   </tr>
   <tr>
       <td>Item 3</td>
       <td>Item 4</td>
   </tr>
</table>

jQuery delegate() method code.
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>

<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
  $("table").delegate("td","click",function(){
         alert('I am' + $(this).text());
  });
});
</script>


It takes 3 arguments.

  1. Selector
  2. Event Type
  3. Event Handler
See live Demo and Code.
You will say that this is very much possible with the bind() method. Below code will serve the purpose.
$(document).ready(function(){         
$("table td").bind("click",function(){
alert('I am' + $(this).text());
});
});
Then what's new with delegate() method?
bind() vs delegate()
bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let's extend our demo and place a button on the page which will add the td dynamically.
$("#btnAdd").click(function(){
$("table").append("<tr><td>Item 5</td><td>Item 6</td></tr>");
});
Now, when you run this page, you will not find click event for newly added td.
See live Demo and Code.

But with delegate(), you will find click event for newly added td.
delegate() method adds event which are on the page and also listens for
new element and add event to them.

See live Demo and Code.

No comments:

Post a Comment

Thank you so much for providing your valuable feedback. I will will look into them and update my skills & technologies accordingly.