Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

EventTarget — receiving and dispatching events

EventTarget is a Web API interface for registering listeners and dispatching events. A standalone instance can be created without a DOM element.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const target = new EventTarget();
target.addEventListener(type, callback, options);
target.removeEventListener(type, callback, options);
const notCanceled = target.dispatchEvent(event);

EventTarget is a Web API interface, not part of the ECMAScript standard. new EventTarget() creates a standalone event target with no parent in the propagation tree.

addEventListener() registers a listener. removeEventListener() requires the same event type, the same callback reference, and a matching capture value. With once: true, the listener registration is automatically removed before its callback is invoked. If the callback dispatches a fresh event of the same type on the same target, the removed registration does not invoke the callback again.

dispatchEvent() invokes listeners synchronously. It returns false if the event’s canceled flag is set; otherwise it returns true. For a cancelable event, both a call to preventDefault() and the legacy assignment event.returnValue = false can set that flag. The result does not indicate whether a listener exists. The example requires an environment that provides EventTarget and Event, but it does not require a browser. It runs unchanged in Node.js 24, which does not establish browser compatibility.

Examples

const target = new EventTarget();
const log = [];

function onPing(event) {
  log.push(event.type);
  event.preventDefault();
}

target.addEventListener('ping', onPing, { once: true });
const first = target.dispatchEvent(new Event('ping', { cancelable: true }));
const second = target.dispatchEvent(new Event('ping', { cancelable: true }));

console.log(log.join(','));
console.log(first);
console.log(second);

Result

ping
false
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources