Created
July 19, 2022 14:55
-
-
Save giangm9/d66c316aefc6191e6fff6162ad8d88c3 to your computer and use it in GitHub Desktop.
Typescript snippets
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
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)) | |
} |
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
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