CKTIS / JavaScript
Event.target a poslucháče vo fáze zachytávania
Rozlíš cieľ udalosti od objektu, na ktorom je zaregistrovaný poslucháč, a zisti, ako voľba `capture` ovplyvňuje poradie volaní v DOM.
Verzia: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
event.target
event.currentTarget
event.eventPhase
node.addEventListener(type, listener, { capture: true })
node.addEventListener(type, listener, true)
node.addEventListener(type, listener)event.target označuje cieľ udalosti z pohľadu poslucháča. event.currentTarget označuje objekt, na ktorom je zaregistrovaný práve volaný poslucháč. Obe vlastnosti sú iba na čítanie. Mimo volania poslucháča má currentTarget hodnotu null; ak objekt potrebuješ neskôr, ulož si ho počas volania.
V bežnom strome DOM udalosť najprv prechádza cez predkov smerom k cieľu. V tejto fáze (Event.CAPTURING_PHASE, 1) sa volajú poslucháče zaregistrované s { capture: true } alebo s true ako tretím argumentom addEventListener(). Predvolená hodnota capture je false.
Na samotnom cieli sa poslucháče so zachytávaním volajú pred poslucháčmi bez zachytávania. Obe skupiny však čítajú rovnakú hodnotu event.eventPhase: Event.AT_TARGET (2). Potom, iba ak je event.bubbles rovné true, sa udalosť vracia cez predkov v opačnom poradí (Event.BUBBLING_PHASE, 3) a volá ich poslucháče bez zachytávania. Vypnutie prebublávania nevypína zachytávanie ani spracovanie na cieli.
Tieto API patria k DOM, nie k ECMAScriptu. V bežnom strome sa target počas šírenia nemení, no na druhej strane hranice Shadow DOM môže označovať hostiteľský prvok namiesto vnútorného uzla.
Príklady
(() => {
// 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 }));
})();Výsledok
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
Spusť kód v konzole prehliadača. Prvky sa nevkladajú do dokumentu a `dispatchEvent()` volá poslucháče synchrónne. V Node.js kód používa zjednodušený model šírenia udalostí namiesto DOM prehliadača. S `bubbles: false` zmizne iba posledný riadok.
Súvisiace lekcie
- JavaScript · Lekcia 40 · Stredne pokročilá · Verzia: 3