I’m trying out jquery as a javascript library over prototype. Now when it comes to event delegation in prototype I can do the following:
$('wrapper').observe('click', function(event) {
var foo = Event.findElement(event, '.foo1');
if (foo) // do something
var bar = Event.findElement(event, '.bar1');
if (bar) // do something else
});
So this means only one click handler is placed on the document.
I know jquery has live/delegate methods, but it seems you need to provide the selector in the call (unless I’m mistaken?). Is there a similar way to have just one click handler and do something similar? Or is it better to split them up as separate events?
Thanks
I think it’s a bit cleaner to split them up. When you look at the result it’s a bit cleaner/easier to maintain. Here’s what
.delegate()would look like:To answer the question yes you can have a single handler, for example:
There are also other approximate methods, e.g. with
.click()and$.contains(). But this and other methods are less efficient and a bit harder to maintain, at least to me, you can decide what’s best, but I’d personally go with the 2 handlers in this case.