views:

135

answers:

4

I'm confused about when you should use event delegation as opposed to out-of-the-box JQuery event handling.

I'm always tempted to use an event handler because it's so easy in JQuery:

For example:

$("button#submit").click(function () { 
      $(this).css("disabled", "true");
    });

Event delegation is not really that much more complex to write:

$("button#submit").live("click", function() {
      $(this).css("disabled", "true");
});

But it just doesn't seem as intuitive.

Is there a simple rule of thumb about when to use event delegation? I guess I don't really understand the point of it.

+3  A: 

Use .live() when you will be dynamically adding elements to the page that need to have that event assigned to them. (note that .live() works only with selectors)

Use .click() (or whatever other event) for all other cases

Darko Z
yarr...thought that was obvious.
Mark
@Mark - Who asked you?
fingerprint
I would still use .live or better still hand rolled event delegation even if I was not adding elements. Why have 100 dom events if I can have just 1.
redsquare
+1  A: 

According to this, it's all about speed when there are lots of bound elements.

David Toso
A: 

I find I'm using live wherever possible. That way if I add dynamic content later, I don't have to change the code at all.

Nosredna
Be wary of .live. Too many live events can impact performance also.
redsquare
I always check performance, and haven't had a case where live has hurt me yet.
Nosredna
have you checked the perf of say 30 .live listerners compared to standard event delegation.
redsquare
No. I'm sure not nearly that many. Is 30 where it starts to breakdown? What is the first browser to get sluggish? IE6?
Nosredna
+2  A: 

You should use event delegation in the following situations:

  • When you want to handle the same event across many elements, e.g. if you have a data table with many rows, using delegation will use much less memory and be faster than registering an event handler per row.
  • When elements are dynamically added to the page after page load and you want to handle events for these new elements, e.g. adding rows to a data table.

Using Event Utility and Event Delegation to Improve Performance disusses this some more (even though the article uses YUI the ideas are still applicable).

wrumsby
Nice answer, thanks. Why community wiki though? Just curious.
fingerprint
I generally enable community wiki by default in case anyone wants to tidy things up.
wrumsby
I see. I thought you were rejecting our societal system of grade-based rewards and incentives. Anyway, thanks for the link. Terrific article.
fingerprint
Anyone with reputation >= 2000 can edit any post, CW or not.
Matthew Crumley