4

I understand that Event Delegation is the propagation of being able to handle events from a parent element to its children elements. Is Event Handling just being able to assign "event handlers" to an element?

EDIT: I also found "this explanation", but it's over my head.

4

3 回答 3

4

"Event handling" means to handle an event, in whatever way you choose.

"Event delegation" is a special kind of event handling, in which an event handler of the parent of an element handles events for that element. There's no difference to regular event handling, it just explicitly describes the case where you let events bubble up to be handled at another element than the original target.

This would look like this in practice:

<div id="foo">
    <a href="#">Bar</a>
</div>

The event handler would be attached to div#foo and catch all, for example, click events. When the event handler catches such an event, it inspects event.target to see if the event originated from a desired source, for example an a element. If it did, it does something, otherwise it ignores the event. That would be an example of the parent (div#foo) handling click events as the delegate of a. div#foo handles events triggered by its child a. a delegates the event handling to div#foo, it does not handle them itself.

Note that when I say "a handles an event", this is less-confusing shorthand for "an event handler attached to a handles the event". :)

于 2013-10-11T15:41:04.997 回答
0

Event handling is just a general term means "processing an event".
Event delegation mostly relates to jQuery.deleate method which is deprecated now. It's all about event propagation. That means handling events on other nodes. Event propagation is about how an event propagated from a node where it happened to higher-level or lower-level nodes. Actually there're two models of propagation: bubbling (up) and capturing (down).

The standard for DOM Events provides both models. But not all browsers support them. Hopefully libraries like jQuery often hide compatibility differences.

See also: http://www.quirksmode.org/js/events_order.html

于 2013-10-11T15:59:40.703 回答
0

"Event handling": to handle an event, usually using addEventListner or anything.

"Event delegation": This is a way of taking advantage of event bubbling to optimize code.

Suppose you have a lot of child element which get generated dynamically and you need an event listener for each. It will end up with a performance issue. So we should proceed with a better approach with the help of event Bubbling.

I have provided a simple example to understand. Where without attaching an event listener to each child element we can still access the data of children.

document.querySelector("#category").addEventListener('click', (e) => {
  console.log(e.target.id);

})
<div>
  <ul id="category">
    <li id="Grocery">Grocery</li>
    <li id="Electronics">Electronics</li>
    <li id="Dress">Dress</li>
  </ul>
</div>

于 2020-03-03T19:23:48.103 回答