Skip to content

Instantly share code, notes, and snippets.

@itsdouges
Created October 21, 2018 22:06
Show Gist options
  • Save itsdouges/10d3f3a6a19242185594f723f1aa844b to your computer and use it in GitHub Desktop.
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.
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