Created
July 30, 2024 18:15
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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