Created
October 21, 2018 22:06
-
-
Save itsdouges/10d3f3a6a19242185594f723f1aa844b to your computer and use it in GitHub Desktop.
Listen to multiple document events in one call, with one call to cleanup.
This file contains 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
export const listenTo = <K extends keyof DocumentEventMap>( | |
type: K | K[], | |
listener: (this: Document, ev: DocumentEventMap[K]) => any, | |
options?: boolean | AddEventListenerOptions | |
) => { | |
if (Array.isArray(type)) { | |
type.forEach(typ => { | |
document.addEventListener(typ, listener, options); | |
}); | |
return () => { | |
type.forEach(typ => { | |
document.removeEventListener(typ, listener, options); | |
}); | |
}; | |
} else { | |
document.addEventListener(type, listener, options); | |
return () => document.removeEventListener(type, listener, options); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment