Skip to content

Instantly share code, notes, and snippets.

@giangm9
Created July 19, 2022 14:55
Show Gist options
  • Save giangm9/d66c316aefc6191e6fff6162ad8d88c3 to your computer and use it in GitHub Desktop.
Save giangm9/d66c316aefc6191e6fff6162ad8d88c3 to your computer and use it in GitHub Desktop.
Typescript snippets
export declare type EventCallback<T> = (arg: T) => any;
export declare type Event<T = any> = EventCallback<T>[];
export function emit<T>(e: Event<T>, data: T) {
e.forEach(callback => callback(data))
}
import { useEffect } from "react";
export function useDocumentEvent<K extends keyof DocumentEventMap>(type: K,
listener: (this: Document, ev: DocumentEventMap[K]) => any,
deps = []
) {
useEffect(() => {
document.addEventListener(type, listener);
return () => {
document.removeEventListener(type, listener);
}
}, deps)
}
export function useWindowEvent<K extends keyof WindowEventMap>(type: K,
listener: (this: Window, ev: WindowEventMap[K]) => any,
deps = []
) {
useEffect(() => {
window.addEventListener(type, listener);
return () => {
window.removeEventListener(type, listener);
}
}, deps)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment