Monday 21 November 2011

jQuery’s on() methods – .bind(), .live(), and .delegate()

Currently we have three different event API pairs: bind/unbind, live/die, and delegate/undelegate. Now  jQuery team have announced in v1.7 a new method for binding events called on. This method combines the functionality of live, bind, and delegate . It allowing you to specify the binding method based the arguments passed rather than by using different function names. bind() and delegate() methods still exist, but the team recommend you use on() and off() for all new projects using jQuery 1.7.
$(elements).on( events [, selector] [, data] , handler );

$('a').bind('click', myHandler);
$('a').on('click', myHandler);

$('form').bind('submit', { val: 42 }, fn);
$('form').on('submit', { val: 42 }, fn);

$(window).unbind('scroll.myPlugin');
$(window).off('scroll.myPlugin');

$('.comment').delegate('a.add', 'click', addNew);
$('.comment').on('click', 'a.add', addNew);

$('.dialog').undelegate('a', 'click.myDlg');
$('.dialog').off('click.myDlg', 'a');

$('a').live('click', fn);
$(document).on('click', 'a', fn);

$('a').die('click');
$(document).off('click', 'a');

No comments:

Post a Comment