A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget below:

EventTarget: EventTarget() constructor - Web APIs

EventTarget: EventTarget() constructor

Baseline Widely available

Note: This feature is available in Web Workers.

The EventTarget() constructor creates a new EventTarget 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 the EventTarget interface, using the super keyword.

Syntax Parameters

None.

Return value

A new instance of the EventTarget object.

Examples Implementing a counter

This example implements a Counter class, with increment() and decrement() methods. It fires a custom "valuechange" event when either of these methods is called.

HTML
<button id="dec" aria-label="Decrement">-</button>
<span id="currentValue">0</span>
<button id="inc" aria-label="Increment">+</button>
JavaScript
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 Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4