Friday, October 10, 2008

jquery.delegate

This is a jquery plugin which handles event delegation. There are a bunch of delegation plugins out there, and this is just an example of additional functionality, that I wanted to try before delegation gets added to the core.

Download - jQuery 1.2.6+ required.

The "delegate" method takes 3 or 4 arguments:

  • type - The type(s) of event being bound/delegated. Seperate multiple events with spaces.
  • selector - The selector(s) to match against event.targets and execute the provided handler. Seperate multiple selectors with commas (extra spaces are allowed).
  • handler - The function to call against the matching selector(s). The scope (this) will be the matched element.
  • data - (optional) Any data to be shared between handlers via the event.data property. Currently, only the initial binding of a delegate handler will bind the data. This will be easily fixed for the next release.

Here are some examples of the API:

// delegate clicks on every span inside a div $('div').delegate( 'click', 'span', function( event ){ $( this ).toggleClass('selected'); });
 
// delegate clicks but stop propagation $('div').delegate( 'click', 'span', function( event ){ $( this ).toggleClass('selected'); return false; });
 
// delegate multiple comma-seperated selectors $('div').delegate( 'click', 'span, div', function( event ){ $( this ).toggleClass('selected'); });
 
// delegate multiple space-seperated events $('div').delegate( 'mouseover mouseout', 'span', function( event ){ $( this ).toggleClass('selected'); });

The "undelegate" method takes 0 to 3:

  • type - (optional) The type(s) of event being unbound. Seperate multiple events with spaces.
  • selector - The selector(s) to be removed. Seperate multiple selectors with commas (extra spaces are allowed).
  • handler - The function to be removed. This must also match the selector that the function was paired with.

Here are some examples of the API:

// undelegate clicks on every span inside a div $('div').undelegate( 'click', 'span' );
 
// undelegate multiple comma-seperated selectors $('div').undelegate( 'click', 'span, div' );
 
// undelegate multiple space-seperated events $('div').undelegate( 'mouseover mouseout', 'span' );
 
// undelegate all selectors for a given event type $('div').undelegate( 'click' );
 
// undelegate every event and every selector $('div').undelegate();

Please direct any feedback to http://groups.google.com/group/threedubmedia