addEventListener
Binds an event handler to an element: the helper compiled templates call for onX and the on: and oncapture: prefixes.
Binds an event handler to an element: the helper compiled templates call for onX and the on:
and oncapture: prefixes. Handlers run batched and untracked, with this set to the element.
Inside an owner, the listener is removed when the owner is disposed, even if the element outlives
it.
Import#
ts
import { addEventListener } from "@shadow-js/web";
Signature#
ts
function addEventListener(
el: Element,
name: string,
handler: unknown,
delegate?: boolean,
capture?: boolean,
): void
Parameters#
| Name | Description |
|---|---|
el |
Target element. |
name |
Event name, lowercase, such as click. |
handler |
A function (called with the event), a [fn, data] tuple (called as fn(data, event)), or a listener object { handleEvent, once, passive, capture, signal }, which is always bound natively with those options. null, undefined and false bind nothing. |
delegate |
true stores the handler on the element for the document listener of delegateEvents (installed on demand) when name is a delegated event (click, input, keydown, pointer, mouse, touch and focus events, ...) and the element has no delegated handler for it yet. Otherwise, and when undefined, the handler gets a native listener. |
capture |
true listens in the capture phase, never delegated. Undefined means the bubble phase. |
Throws#
- TypeError
SHADOW_EVENT_HANDLERwhenhandleris not a function, a tuple whose first item is a function, or a listener object.
Examples#
ts
import { addEventListener } from "@shadow-js/web";
const button = document.createElement("button");
addEventListener(button, "click", () => console.log("pressed"), true);
addEventListener(button, "focus", [(id: string, event: Event) => console.log(id, event.type), "save"]);