Sunday, November 20, 2011

jQuery’s on() methods

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);


$('.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);

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

No comments: