9.20.2012

jQuery.live() vs jQuery.delegate()

Difference between jQuery live() and delegate()

S.No
jQuery.live()
jQuery.delegate()
1
Whether it can be used with chaining or not ?
live() cannot be used with chaining .So, the below thing cannot be done,

$(‘#foo’).children(‘table’).find(‘td’).live(‘click’, function(){
blah blah...
});
Whether it can be used with chaining or not ?
delegate() can be used with chaining as provided below,

$(‘#foo’).children(‘table’).delegate(‘tr’, ‘click’, function(){
blah blah...
});

2
Performance:
Live() default context is document…. so it bubble till document which cause the performance issue.

But, in jQuery 1.4 , option is provided to define context for live other than document as given below,

$(‘a’, $(‘#mytable’)[0]).live(‘click’, function(){
blah blah...
});

Note: Context is defining the search limit to bubble to top level of element.
Performance:
In delegate we can set context which cause less traverse

$(‘#mytable’).delegate(‘a’,‘click’, function(){
blah blah...
});

Summary:
  1. Both live() and delegate() are used to attach event to current element and future elements which we append after DOM loaded e.g. we load some table rows using ajax.
  2. By considering performance factor,so it is better to use delegate all the time instead of live() and bind().
Reference:


No comments:

Post a Comment