A live binding fun fact

jQuery allows event delegation using .live().

When using jQuery there are instances where I have to bind my events to the document root, i.e. $(document). My impression was that ‘live’ should also work with this root. But it does not. Consider the following example.

<script language = "JavaScript" type = "text/javascript">
  $(document).ready(function (){

  $(document).bind('custom_event.am', function(){
      alert('Bind works with document root!');
   });
   
   $(document).trigger('custom_event.am');
  
  $(document).live('custom_event1.am', function(){
      alert('Live does not work with document root!');
   });
   
   $('#am_wrapper').trigger('custom_event1.am');
   
  });
  
</script>

But if we use anything other than the document root, there is no problem. Consider the following example.

<script language = "JavaScript" type = "text/javascript">
  $(document).ready(function (){

  $('#am_wrapper').live('custom_event1.am', function(){
      alert('Live now works!');
   });
   
   $('#am_wrapper').trigger('custom_event1.am');
   
  });
  

</script>
<div id = "am_wrapper">  </div>

To unravel the mystery I delved into the jQuery source code and concluded the following.

Live events are bound to the document root. So when a ‘live’ event fires it bubbles up to the document root. A special handler function first called(‘liveHandler’). Before it executes the custom(your) handler it makes an attempt to gather all the binding for the the said event. To do this it runs this statement:

match = jQuery( event.target ).closest( selectors, event.currentTarget );

This fails because ‘closest’ starts from the current element and moves upwards. As the target and current target both are the document root there is no where to go. As there are no matches(match.length === 0) the function exits without doing much.

Even if it wasn’t for this caveat I am not a big fan of binding my events to the root. Would prefer to reserve a top level element to store all my bindings.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s