import { deepFreeze } from '../utils' export type EventMapEmpty = Record export type EventListener = (data: D) => void export type Off = () => void export default function EventBus() { const listeners = {} as Record[]> function on(type: EK, listener: EventListener): Off { listeners[type] = (listeners[type] || []).concat(listener) return () => off(type, listener) } function off(type: EK, listener: EventListener) { listeners[type] = (listeners[type] || []).filter((l) => l !== listener) } function dispatch(type: EK, data: EventMap[EK]) { if (!(type in listeners)) return ;(listeners[type] as EventListener[]).forEach((l) => l(data)) } return deepFreeze({ on, off, dispatch, }) }