CKTIS / JavaScript
Event.target y escuchas en la fase de captura
Distingue el objetivo del evento del objeto en el que se registró la escucha y descubre cómo `capture` cambia el orden de las llamadas en el DOM.
Versión: ECMAScript 2024 and the current web platform; runtime support varies
Sintaxis
event.target
event.currentTarget
event.eventPhase
node.addEventListener(type, listener, { capture: true })
node.addEventListener(type, listener, true)
node.addEventListener(type, listener)event.target indica el objetivo del evento tal como lo ve la función de escucha. event.currentTarget indica el objeto en el que se registró la función que se está ejecutando. Ambas propiedades son de solo lectura. Fuera de la llamada a una función de escucha, currentTarget vale null; guarda el objeto durante la llamada si lo necesitas más tarde.
En un árbol DOM ordinario, el evento recorre primero los ancestros hacia el objetivo. En esta fase (Event.CAPTURING_PHASE, 1) se ejecutan las funciones registradas con { capture: true } o con true como tercer argumento de addEventListener(). El valor predeterminado de capture es false.
En el propio objetivo, las funciones de captura se ejecutan antes que las demás, pero ambos grupos leen el mismo valor de event.eventPhase: Event.AT_TARGET (2). Después, solo si event.bubbles vale true, el evento vuelve por los ancestros en orden inverso (Event.BUBBLING_PHASE, 3) y ejecuta sus funciones sin captura. Desactivar el burbujeo no desactiva la captura ni el procesamiento en el objetivo.
Estas API pertenecen al DOM, no a ECMAScript. En un árbol ordinario, target no cambia durante la propagación, pero al cruzar un límite del Shadow DOM puede señalar al elemento anfitrión en lugar del nodo interno.
Ejemplos
(() => {
// Node.js has no DOM tree. This fallback models only the propagation used here.
class DemoNode {
#parent = null;
#listeners = [];
append(child) {
child.#parent = this;
}
addEventListener(type, listener, options) {
const capture = options === true || options?.capture === true;
this.#listeners.push({ type, listener, capture });
}
dispatchEvent(event) {
const ancestors = [];
for (let node = this.#parent; node !== null; node = node.#parent) {
ancestors.push(node);
}
let currentTarget = null;
let phase = Event.NONE;
Object.defineProperties(event, {
target: { configurable: true, get: () => this },
currentTarget: { configurable: true, get: () => currentTarget },
eventPhase: { configurable: true, get: () => phase }
});
const invoke = (node, nextPhase, capture) => {
currentTarget = node;
phase = nextPhase;
for (const entry of node.#listeners.slice()) {
if (entry.type === event.type && entry.capture === capture) {
entry.listener.call(node, event);
}
}
};
try {
for (let i = ancestors.length - 1; i >= 0; i--) {
invoke(ancestors[i], Event.CAPTURING_PHASE, true);
}
invoke(this, Event.AT_TARGET, true);
invoke(this, Event.AT_TARGET, false);
if (event.bubbles) {
for (const node of ancestors) {
invoke(node, Event.BUBBLING_PHASE, false);
}
}
} finally {
currentTarget = null;
phase = Event.NONE;
}
return !event.defaultPrevented;
}
}
const createElement = (tag) =>
typeof document === 'undefined' ? new DemoNode() : document.createElement(tag);
const parent = createElement('div');
const child = createElement('button');
parent.id = 'parent';
child.id = 'child';
parent.append(child);
const report = (label) => (event) => {
console.log(`${label}: target=${event.target.id}, currentTarget=${event.currentTarget.id}, phase=${event.eventPhase}`);
};
parent.addEventListener('demo', report('parent bubble'));
child.addEventListener('demo', report('child non-capture'));
parent.addEventListener('demo', report('parent capture'), { capture: true });
child.addEventListener('demo', report('child capture'), { capture: true });
child.dispatchEvent(new Event('demo', { bubbles: true }));
})();Resultado
parent capture: target=child, currentTarget=parent, phase=1 child capture: target=child, currentTarget=child, phase=2 child non-capture: target=child, currentTarget=child, phase=2 parent bubble: target=child, currentTarget=parent, phase=3
Ejecuta el código en la consola del navegador. Los elementos no se insertan en el documento y `dispatchEvent()` llama a las funciones de forma síncrona. En Node.js, el código usa un modelo simplificado de propagación en lugar del DOM del navegador. Con `bubbles: false`, solo desaparece la última línea.
Lecciones relacionadas
- JavaScript · Lección 40 · Intermedio · Versión: 3