Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / JavaScript

Event.target e listener nella fase di cattura

Distingui il destinatario dell’evento dall’oggetto su cui è registrato il listener e scopri come `capture` cambia l’ordine delle chiamate nel DOM.

Versione: ECMAScript 2024 and the current web platform; runtime support varies

Sintassi

event.target
 event.currentTarget
 event.eventPhase
 node.addEventListener(type, listener, { capture: true })
 node.addEventListener(type, listener, true)
 node.addEventListener(type, listener)

event.target indica il destinatario dell’evento dal punto di vista del listener. event.currentTarget indica l’oggetto su cui è registrato il listener in esecuzione. Entrambe le proprietà sono di sola lettura. Al di fuori della chiamata al listener, currentTarget vale null: salva l’oggetto durante la chiamata se ti serve in seguito.

In un normale albero DOM, l’evento percorre prima gli antenati in direzione del destinatario. In questa fase (Event.CAPTURING_PHASE, 1) vengono chiamati i listener registrati con { capture: true } oppure con true come terzo argomento di addEventListener(). Il valore predefinito di capture è false.

Sul destinatario stesso, i listener di cattura precedono quelli senza cattura, ma entrambi i gruppi leggono lo stesso valore di event.eventPhase: Event.AT_TARGET (2). Poi, solo se event.bubbles vale true, l’evento risale gli antenati in ordine inverso (Event.BUBBLING_PHASE, 3) e chiama i loro listener senza cattura. Disattivare il bubbling non disattiva la cattura né la gestione sul destinatario.

Queste API appartengono al DOM, non a ECMAScript. In un albero normale, target non cambia durante la propagazione, ma oltre un confine dello Shadow DOM può indicare l’elemento host anziché il nodo interno.

Esempi

(() => {
  // 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 }));
})();

Risultato

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

Esegui il codice nella console del browser. Gli elementi non vengono inseriti nel documento e `dispatchEvent()` chiama i listener in modo sincrono. In Node.js il codice usa un modello semplificato di propagazione al posto del DOM del browser. Con `bubbles: false` scompare solo l’ultima riga.

Lezioni correlate

  • JavaScript · Lezione 40 · Intermedio · Versione: 3

Fonti