index.ts
This file
Path
src/index.ts
75 lines · 2.4 KiB · TypeScript
Last changed by
Migrate to TypeScript and use Map (#99)Jack Franklinbefore adoptionbe5237f
History of this fileTake it
Migrate to TypeScript and use Map (#99)Jack Franklinbefore adoptionbe5237f
lines 1–75why, one step back1type EventType = string | symbol;23// An event handler can take an optional event argument4// and should not return a value5type Handler = (event?: any) => void;6type WildcardHandler= (type: EventType, event?: any) => void78// An array of all currently registered event handlers for a type9type EventHandlerList = Array<Handler>;10type WildCardEventHandlerList = Array<WildcardHandler>;1112// A map of event types and their corresponding event handlers.13type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;1415export interface Emitter {16 on(type: EventType, handler: Handler): void;17 on(type: "*", handler: WildcardHandler): void;1819 off(type: EventType, handler: Handler): void;20 off(type: "*", handler: WildcardHandler): void;2122 emit<T = any>(type: EventType, event?: T): void;23 emit(type: "*", event?: any): void;24}2526/** Mitt: Tiny (~200b) functional event emitter / pubsub.27 * @name mitt28 * @returns {Mitt}29 */30export default function mitt(all: EventHandlerMap): Emitter {31 all = all || new Map();3233 return {34 /**35 * Register an event handler for the given type.36 *37 * @param {string|symbol} type Type of event to listen for, or `"*"` for all events38 * @param {Function} handler Function to call in response to given event39 * @memberOf mitt40 */41 on(type: EventType, handler: Handler) {42 const handlers = (all.get(type) || []);43 handlers.push(handler);44 all.set(type, handlers);45 },4647 /**48 * Remove an event handler for the given type.49 *50 * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"`51 * @param {Function} handler Handler function to remove52 * @memberOf mitt53 */54 off(type: EventType, handler: Handler) {55 if (all.has(type)) {56 all.get(type).splice(all.get(type).indexOf(handler) >>> 0, 1);57 }58 },5960 /**61 * Invoke all handlers for the given type.62 * If present, `"*"` handlers are invoked after type-matched handlers.63 *64 * Note: Manually firing "*" handlers is not supported.65 *66 * @param {string|symbol} type The event type to invoke67 * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler68 * @memberOf mitt69 */70 emit(type: EventType, evt: any) {71 ((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); });72 ((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); });73 }74 };75}