EventTarget: EventTarget() constructor
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
Note: This feature is available inWeb Workers.
TheEventTarget() constructor creates a newEventTarget object instance.
Note:It is fairly rare to explicitly call this constructor. Most of the time, this constructor is used inside the constructor of an object extending theEventTarget interface, using thesuper keyword.
In this article
Syntax
js
new EventTarget()Parameters
None.
Return value
A new instance of theEventTarget object.
Examples
>Implementing a counter
This example implements aCounter class, withincrement() anddecrement() methods. It fires a custom"valuechange" event when either of these methods is called.
HTML
html
<button aria-label="Decrement">-</button><span>0</span><button aria-label="Increment">+</button>JavaScript
js
class Counter extends EventTarget { constructor(initialValue = 0) { super(); this.value = initialValue; } #emitChangeEvent() { this.dispatchEvent(new CustomEvent("valuechange", { detail: this.value })); } increment() { this.value++; this.#emitChangeEvent(); } decrement() { this.value--; this.#emitChangeEvent(); }}const initialValue = 0;const counter = new Counter(initialValue);document.querySelector("#currentValue").innerText = initialValue;counter.addEventListener("valuechange", (event) => { document.querySelector("#currentValue").innerText = event.detail;});document.querySelector("#inc").addEventListener("click", () => { counter.increment();});document.querySelector("#dec").addEventListener("click", () => { counter.decrement();});Result
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-eventtarget-eventtarget①> |