export type EventType = string | symbol; // An event handler can take an optional event argument // and should not return a value export type Handler = (event: T) => void; export type WildcardHandler> = ( type: keyof T, event: T[keyof T] ) => void; // An array of all currently registered event handlers for a type export type EventHandlerList = Array>; export type WildCardEventHandlerList> = Array>; // A map of event types and their corresponding event handlers. export type EventHandlerMap> = Map< keyof Events | '*', EventHandlerList | WildCardEventHandlerList >; type GenericEventHandler> = | Handler | WildcardHandler; export class EventEmitter> { /** * A Map of event names to registered handler functions. */ public all: EventHandlerMap; public constructor() { this.all = new Map(); } on(type: Key, handler: Handler): void; on(type: '*', handler: WildcardHandler): void; /** * Register an event handler for the given type. * @param {string|symbol} type Type of event to listen for, or `'*'` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ public on(type: Key, handler: GenericEventHandler) { const handlers: Array> | undefined = this.all!.get(type); if (handlers) { handlers.push(handler); } else { this.all!.set(type, [handler] as EventHandlerList); } } off(type: Key, handler?: Handler): void; off(type: '*', handler: WildcardHandler): void; /** * Remove an event handler for the given type. * If `handler` is omitted, all handlers of the given type are removed. * @param {string|symbol} type Type of event to unregister `handler` from, or `'*'` * @param {Function} [handler] Handler function to remove * @memberOf mitt */ public off(type: Key, handler?: GenericEventHandler) { const handlers: Array> | undefined = this.all!.get(type); if (handlers) { if (handler) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); } else { this.all!.set(type, []); } } } emit(type: Key, event: Events[Key]): void; emit(type: undefined extends Events[Key] ? Key : never): void; /** * Invoke all handlers for the given type. * If present, `'*'` handlers are invoked after type-matched handlers. * * Note: Manually firing '*' handlers is not supported. * * @param {string|symbol} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit(type: Key, evt?: Events[Key]) { let handlers = this.all!.get(type); if (handlers) { (handlers as EventHandlerList) .slice() .map((handler) => { handler(evt!); }); } handlers = this.all!.get('*'); if (handlers) { (handlers as WildCardEventHandlerList) .slice() .map((handler) => { handler(type, evt!); }); } } }