Event
Event Model
An event system implemented by browsers to allows users to create/trigger/subscribe/remove events.
Event bubbling
Event bubbling is a propagation mechanism in the DOM where an event is first triggered on the target element that initiated the event and then propagates upward through the DOM tree to the root of the document.
To stop the event from keep bubbling, stopPropagation()
can be called in the event handler to prevent it.
Event bubbling is the core for a technique called event delegation, where a single event handler is attached to a common ancestor of multiple elements such that all children events can be single-handedly handled in the ancestor, improving code simplicity and performance.
Event capturing
Event capturing is a mechanism that follows the opposite order of event bubbling, where event handlers on the ancestors are triggered first then passed on to children.
Event Delegation
A technique where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. This brings benifits such as:
- Improved performance
- Simplified event handling
- Dynamic element support
However, not all events can be delegated because they are not bubbled. Non-bubbling events include: focus
, blur
, scroll
, mouseenter
, mouseleave
, resize
, etc.
Deep Dive
this
in the callback
When using the addEventListener
method, the value of this
might differ depending how the attached handler function is declared.
my_element.addEventListener("click", function (e) {
console.log(this.className); // logs the className of my_element
console.log(e.currentTarget === this); // true
});
// Arrow function do not have their own this context
my_element.addEventListener("click", (e) => {
console.log(this.className); // WARNING: `this` is not `my_element`
console.log(e.currentTarget === this); // logs `false`
});
References
Introducing to Events -- mdn web docs
- 6. Document Object Model Events -- w3.org
- DOM Events Capture/Bubble Visualization
- Event order
- EventTarget: addEventListener() method -- mdn web docs
- Bubbling and Capturing -- JavaScript.info