Is there a rule for using event delegation versus event handling in jQuery?

I am confused when you need to use event delegation rather than jQuery event handling out of the box.

I am always tempted to use an event handler because it is so simple in jQuery:

For example:

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

Event delegation is actually not that difficult to write:

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

But that just doesn't seem intuitive.

Is there a simple rule about when to use event delegation? I think that I do not quite understand its essence.

+3
source share
4 answers

You should use event delegation in the following situations:

  • , . , , .
  • , , . .

( YUI, ).

+2

.live(), , . ( , .live() )

.click() ( )

+3

According to this , it's all about speed when there are many related elements.

+1
source

I find that I use live wherever possible. That way, if I add dynamic content later, I don’t need to change the code at all.

0
source

Source: https://habr.com/ru/post/1713018/


All Articles