22 lines
642 B
TypeScript
22 lines
642 B
TypeScript
|
|
export type AppEvents = {
|
||
|
|
"player:open": { name: string };
|
||
|
|
};
|
||
|
|
|
||
|
|
export function dispatchAppEvent<K extends keyof AppEvents>(
|
||
|
|
name: K,
|
||
|
|
detail: AppEvents[K]
|
||
|
|
): void {
|
||
|
|
if (typeof window === "undefined") return;
|
||
|
|
window.dispatchEvent(new CustomEvent(name, { detail }));
|
||
|
|
}
|
||
|
|
|
||
|
|
export function onAppEvent<K extends keyof AppEvents>(
|
||
|
|
name: K,
|
||
|
|
handler: (detail: AppEvents[K]) => void
|
||
|
|
): () => void {
|
||
|
|
if (typeof window === "undefined") return () => {};
|
||
|
|
const listener = (e: Event) => handler((e as CustomEvent<AppEvents[K]>).detail);
|
||
|
|
window.addEventListener(name, listener);
|
||
|
|
return () => window.removeEventListener(name, listener);
|
||
|
|
}
|