Halhelms
SIGN UP FOR MY NEWSLETTER
 
 
Halhelms

Shameless Money

Recent Comments

Recent Entries

RSS

Subscribe

jQuery Ate My Homework

Well, I had my January newsletter almost wrapped. The centerpiece was an article on event delegation. That's a technique used to get around the limitation that an element added to the DOM does not "inherit" events that may have been bound to other, similar elements.

An example: if I bind all images' "mouseover" function so that a tooltip appears, and then add another image element dynamically to the DOM, that new image won't have the desired mouseover behavior.

The solution is...err...was something known as "event delegation", that takes advantage of "event bubbling". With this techique, you don't bind the image, but a parent of the image that will always be available. Then, at run time, you look for a mouseover of the event target and execute code if the event target is (in my example) an image.

So, I had my newsletter all set; I wrote some code to show the technique being used, wrote up a tutorial -- and then happened to be looking at the new features of jQuery 1.3. There's a new method, "live", that does the event binding for you. Like all of jQuery, it's *really hard* to use:

$('img').live(function(...));

There are some limitations on it, but I strongly suspect these will be removed in short order. So, thanks for eating my homework, jQuery!

Years ago, I kidded with Sim Simeonov, one of the original architects of ColdFusion, that what we needed was a DWIM function. That's "DWIM" as in "Do What I Mean". Now, I'm just waiting for jQuery to come up with that next.

Comments
andy matthews's Gravatar Actually jQuery, via the liveQuery plugin, has had this capability for several versions. The jQuery team has been talking about moving this functionality into the core...I'm glad they finally did it.
# Posted By andy matthews | 2/2/09 11:40 AM
Adrian Lynch's Gravatar Another way to maintain bound events is to use clone on a DOM element that already has the events.

But this means you then have to change attributes in the clone (image source in your case Hal) and you have to have at least one of these elements in the page to start.

Probably best off using live() really!
# Posted By Adrian Lynch | 2/6/09 11:51 AM
 
   
Clicky Web Analytics