Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created July 30, 2024 18:15
Show Gist options
  • Save colelawrence/da94a445dce6f075c6c8b73acf2bc11e to your computer and use it in GitHub Desktop.
Save colelawrence/da94a445dce6f075c6c8b73acf2bc11e to your computer and use it in GitHub Desktop.
Listen to event targets, returning the unsubscribe function. TypeScript types included for DOM
interface listen {
<K extends keyof HTMLElementEventMap>(
target: HTMLElement,
type: K,
listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions,
): () => void;
(
target: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): () => void;
}
/** Listen to events on the target and return an unsubscribe function */
export const listen: listen = (
target: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
) => {
target.addEventListener(type, listener, options);
return () => target.removeEventListener(type, listener, options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment