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.

fingerprint
  • 93
  • 1
  • 4

4 Answers4

3

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
  • 38,310
  • 15
  • 80
  • 107
2

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).

Walter Rumsby
  • 7,435
  • 5
  • 41
  • 36
1

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

David-SkyMesh
  • 5,041
  • 1
  • 31
  • 38
0

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
  • 83,000
  • 15
  • 95
  • 122