2

I'm learning JavaScript and crossed over Event Bubbling and Event Delegation. I know what Event Bubbling is (goes from a child until Window Object), but I saw that everybody says that Event Delegation is the opposite, and they do some If statements matching the Event target with the element that they want to access. Now I'm wondering...
Why not use 'querySelectorAll' for multiple elements?
And why is considered the opposite of Event Bubbling?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
  • 3
    If you have 100 buttons with onclick handlers, it's usually simpler to put them in a container, assign onclick to this container and use event.target to find out which button has been clicked. This is what "event delegation" does. – georg May 08 '19 at 18:35
  • "*everybody says that Event Delegation is the opposite [of Event Bubbling]*" - that's just plain wrong. Where did you read/hear this? – Bergi May 08 '19 at 18:57

1 Answers1

2

A few benefits:

  • If you have 1000 buttons, it's better to add one click handler on an ancestor element that listens for a click on the descendant buttons, than going through all 1000 buttons and attaching a handler each. The iteration through 1000 elements alone is a performance issue, worse if more. Not to mention the memory usage involved for 1000 buttons to reference the handler.

  • You can listen for events on an element that may not exist yet or doesn't exist yet. You can attach a click handler ahead of time for a descendant button that may not be there. This is commonly used when the content being listened is loaded via AJAX.

  • You can persist handlers across DOM changes. Usually used with dynamic content. For instance, you can a click handler for a todo list item's delete button once. Every time you attach/reattach/detach a todo list item, you don't have to clean up its handlers. You can leave the delegated one alone.

Delegation, is just that, to delegate, to entrust to another. In this case, it's handing the responsibility of holding the event handler from an element to its ancestor. And for this to work, it has to use bubbling.

And bubbling is just half the story. The opposite of bubbling is capturing.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Joseph
  • 107,072
  • 27
  • 170
  • 214