Skip to content
0

katanakit-js / useOn

Function: useOn() ​

ts
function useOn<K>(
   target, 
   event, 
   callback, 
   options?
): (() => void) | null;

Defined in: src/infrastructure/dom/dom.service.ts:362

Attaches an event listener to the target element and returns a cleanup function.

Type Parameters ​

Type ParameterDescription
K extends keyof HTMLElementEventMapThe event type key from HTMLElementEventMap.

Parameters ​

ParameterTypeDescription
targetstring | EventTargetAn EventTarget instance or a CSS selector string.
eventKThe event name to listen for.
callback(event) => voidThe event handler.
options?boolean | AddEventListenerOptionsOptional addEventListener options.

Returns ​

(() => void) | null

A function that removes the listener, or null if not in a browser.

Example ​

ts
const off = useOn("#btn", "click", (e) => console.log("clicked", e));
// later:
off?.();

Released under the MIT License.