EventTarget
The EventTarget interface of Azion Runtime: its constructor and the methods that add and remove event listeners and dispatch events.
The EventTarget interface represents an object that receives events and runs the listeners registered for them. Every event target implements its three methods: addEventListener(), removeEventListener(), and dispatchEvent(). For more information, refer to EventTarget on MDN Web Docs.
In a function, globalThis is an event target. The global addEventListener registers the fetch handler on it, and a listener for a custom event type runs when globalThis.dispatchEvent() dispatches that type. Create your own event targets to build objects that dispatch and listen for custom events while a function handles a request. Add and remove listeners at run time to control which handlers react to an event.
In a browser, the most common event targets are elements and their children, Document, and Window. Objects such as XMLHttpRequest, AudioNode, and AudioContext are event targets too. Elements, documents, and windows also accept event handlers through onevent properties and attributes. A function has no document object: a reference to it throws ReferenceError: document is not defined.
Constructor
EventTarget() creates an event target with no listeners. A class that extends EventTarget inherits the three methods: an instance of class Bus extends EventTarget {} runs the listeners added to it.
Methods
| Method | Description |
|---|---|
target.addEventListener(type, listener, options) | Registers listener for events of type. With { once: true } as options, the listener runs on the first dispatch only. |
target.removeEventListener(type, listener) | Removes the listener registered with the same type and listener. Later dispatches of type do not run it. |
target.dispatchEvent(event) | Dispatches event to the listeners registered for its type. Returns false when event is cancelable and a listener calls preventDefault(). |
dispatchEvent() takes an Event, such as new Event('ping', { cancelable: true }), or a CustomEvent. A listener reads the detail value of a CustomEvent from event.detail.
Example
This handler registers a listener on an event target, dispatches the event, removes the listener, and dispatches the event again. It returns the number of times the listener ran and the event types it received:
The function returns these values. The listener runs once, because the second dispatch comes after removeEventListener():