CKTIS / JavaScript
Event.target e ouvintes na fase de captura
Distingue o alvo do evento do objeto em que o ouvinte foi registado e vê como `capture` altera a ordem das chamadas no DOM.
Versão: ECMAScript 2024 and the current web platform; runtime support varies
Sintaxe
event.target
event.currentTarget
event.eventPhase
node.addEventListener(type, listener, { capture: true })
node.addEventListener(type, listener, true)
node.addEventListener(type, listener)event.target indica o alvo do evento tal como é visto pelo ouvinte. event.currentTarget indica o objeto em que foi registado o ouvinte que está a ser executado. Ambas as propriedades são só de leitura. Fora da chamada ao ouvinte, currentTarget é null; guarda o objeto durante a chamada se precisares dele mais tarde.
Numa árvore DOM normal, o evento percorre primeiro os antepassados em direção ao alvo. Nesta fase (Event.CAPTURING_PHASE, 1), são chamados os ouvintes registados com { capture: true } ou com true como terceiro argumento de addEventListener(). O valor predefinido de capture é false.
No próprio alvo, os ouvintes de captura são executados antes dos ouvintes sem captura, mas ambos os grupos leem o mesmo valor de event.eventPhase: Event.AT_TARGET (2). Depois, só se event.bubbles for true, o evento volta a percorrer os antepassados em ordem inversa (Event.BUBBLING_PHASE, 3) e chama os seus ouvintes sem captura. Desativar a propagação ascendente não desativa a captura nem o tratamento no alvo.
Estas APIs pertencem ao DOM, não ao ECMAScript. Numa árvore normal, target mantém-se durante a propagação, mas, do outro lado de um limite do Shadow DOM, pode indicar o elemento anfitrião em vez do nó interno.
Exemplos
(() => {
// 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
Executa o código na consola do navegador. Os elementos não são inseridos no documento e `dispatchEvent()` chama os ouvintes de forma síncrona. No Node.js, o código usa um modelo simplificado de propagação em vez do DOM do navegador. Com `bubbles: false`, só desaparece a última linha.
Lições relacionadas
- JavaScript · Lição 40 · Intermédio · Versão: 3