enhancement for event delegation and the context-parameter

enhancement for event delegation and the context-parameter

One week ago I wrote an article about the new possibility to use the
context-Parameter in conjunction with the live method (it´s in german:
http://www.protofunc.com/2009/12/08/jquery-live-methode-braucht-jquery-14-eine-neue-api-fur-event-delegation/).
I think we need an additional method, wich gives the developer more
control over the element, to wich the eventlistener will be bound.
The current live-method, allows you to use the context-parameter, but
this option doesn´t really give you the possibility to decide, to wich
element(s) the listener is bound.
To make this more clear. Here are some examples:
1. The following code works and the eventlistener is bound to the
document
$('li', $('#nav')).live('click'....
2. The following code works, as long as #nav is available, and the
eventlistener is bound to the #nav-element (very error-prone)
$('li', $('#nav')[0]).live('click'....
If you have several elements, to wich the element should be bound,
jQuery doesn´t give you a straight forward method to do this:
1. The eventlistener is bound to the document
$('div.teaser', $('div.teaser-wrapper')).live('click'
2. The following code would be invalid
$( 'div.teaser', $('div.teaser-wrapper').get() ).live('click'
I came up with a very simple and short plugin, wich looks like this:
(function($){
var dummy = $([]);
$.each({addLive: 'live', removeLive: 'die'}, function(name,
jMethod){
$.fn[name] = function(sel){
var args = (this[0]) ? Array.prototype.slice.call
(arguments, 1) : [];
return this.each(function(){
dummy.selector = sel;
dummy.context = this;
$.fn[jMethod].apply(dummy, args);
});
};
});
})(jQuery);
With this plugin you can write code like this:
$('div.teaser-wrapper').addLive('div.teaser', 'click', function()
{...});
This gives you a clear and short way to setup event delegation on
specific elements.
Additionally the method could improve event delegation in two ways:
a) use of comma seperated selectors (buggy in jQuerys live-method):
$('div.teaser-wrapper').addLive('div.teaser, div.teaser-box', 'click',
function(){...});
b) add a (very) minimal performance-gain (only elements, wich are
needed to setup the listener are selected)
I know, that you have declined similiar suggestions in the past, but
event delegation gives you a lot of options, wich can´t be controlled
with the current live-method.
--