export type EventType = string | symbol // An event handler can take an optional event argument // and should not return a value export type Handler = (...payload: T[]) => any // An array of all currently registered event handlers for a type export type EventHandlerList = Handler[] export type Payloads = T[] // A map of event types and their corresponding event handlers. export type EventHandlerMap = Map< EventType, { h: EventHandlerList; p?: Payloads } > export interface Emitter { all: EventHandlerMap; on: (type: EventType, handler: Handler) => void; off: (type: EventType, handler: Handler) => void; emit: (type: EventType, ...payload: T[]) => void; } export default function emitter(all: EventHandlerMap = new Map()): Emitter { function execHandler(handler: Handler, payloads: Payloads) { try { handler(...payloads) } catch (err) { console.error('[BCS] Extension error:', err) } } /** * Invoke all handlers for the given type. * * @param {string|symbol} type The event type to invoke * @param {Any} [payload] Any value (object is recommended and powerful), passed to each handler */ function emit(type: EventType, ...payloads: Payloads) { const handlers = all.get(type) if (handlers) { if (handlers.h.length) { (handlers.h as EventHandlerList).forEach((handler) => { execHandler(handler, payloads) }) } else { handlers.p = payloads } } else { all.set(type, { h: [], p: payloads, }) } } return { /** * A Map of event names to registered handler functions. */ all, /** * Register an event handler for the given type. * @param {string|symbol} type Type of event to listen for * @param {Function} handler Function to call in response to given event */ on(type: EventType, handler: Handler) { const handlers = all.get(type) if (handlers) { handlers.h.push(handler) if (handlers.h?.length < 2 && handlers.p) { execHandler(handler, handlers.p) handlers.p = undefined } } else { all.set(type, { h: [handler], p: undefined, }) } }, /** * Remove an event handler for the given type. * @param {string|symbol} type Type of event to unregister `handler` from * @param {Function} handler Handler function to remove */ off(type: EventType, handler: Handler) { const handlers = all.get(type)?.h if (handlers) { // eslint-disable-next-line handlers.splice(handlers.indexOf(handler) >>> 0, 1) } }, emit, } }