To handle click delegation I took the approach of enhancing the click
event using the special events framework.  This might be a slight
tangent to this thread, but it does address many of the problems
discussed here.  Here's the code:

http://webdev.stephband.info/events/click/js/jquery.event.click.js

It allows you to bind a click as normal, but if you pass in an options
object with the properties 'selector' or 'href' the bound function
fires only when the conditions are met:

jQuery('context')
.bind('click', {
    selector: 'h3'
}, handlerFunction);

will fire handlerFunction whenever an h3 (or anything inside an h3) in
'context' is clicked. Since I find 90% of my click bindings are on
links, and I'm often interested in sorting links by type, I also
provide a way to bind to links by type of href:

jQuery('context')
.bind('click', {
    href: 'hash'
}, handlerFunction);

will fire handlerFunction when an anchor with href = "#xxx" is
clicked.  Similarily, it will take the values 'slash' ( /xxx ),
'url' ( xxx://xxx ), 'empty' ( # ), or an exact match for your href.
One more example:

jQuery('context')
.bind('click', {
    selector: 'a[target=overlay]'
    href: 'url'
}, handlerFunction);

will fire handlerFunction on links with target="overlay" and an href
that is a full url.

It caches the results of .closest() so when the same element is
clicked twice .closest() is only run the first time.  Inside
handlerFunction, e.target is set to the selected element (even if it
was an element inside that element that was originally clicked) for
easy manipulation.

As a solution, I like it because it allows me to continue write
bindings the same way as I always have, but just enhance them with an
options object when I want delegation.  I never published it on
jQuery.com, for some reason... perhaps I never considered it entirely
finished. But I have had it working in a couple of website projects.

Cheers,
Stephen.

--

You received this message because you are subscribed to the Google Groups 
"jQuery Development" group.
To post to this group, send email to jquery-...@googlegroups.com.
To unsubscribe from this group, send email to 
jquery-dev+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/jquery-dev?hl=en.


Reply via email to