aboutsummaryrefslogtreecommitdiff
path: root/src/index.ts
blob: f0a2ebb9455c9b19ffab9b458e32abc2488bd8c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
type EventType = string | symbol;

// An event handler can take an optional event argument
// and should not return a value
type Handler = (event?: any) => void;
type WildcardHandler= (type: EventType, event?: any) => void

// An array of all currently registered event handlers for a type
type EventHandlerList = Array<Handler>;
type WildCardEventHandlerList = Array<WildcardHandler>;

// A map of event types and their corresponding event handlers.
type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;

export interface Emitter {
	on(type: EventType, handler: Handler): void;
	on(type: "*", handler: WildcardHandler): void;

	off(type: EventType, handler: Handler): void;
	off(type: "*", handler: WildcardHandler): void;

	emit<T = any>(type: EventType, event?: T): void;
	emit(type: "*", event?: any): void;
}

/** Mitt: Tiny (~200b) functional event emitter / pubsub.
 *  @name mitt
 *  @returns {Mitt}
 */
export default function mitt(all: EventHandlerMap): Emitter {
	all = all || new Map();

	return {
		/**
		 * 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
		 */
		on(type: EventType, handler: Handler) {
			const handlers = (all.get(type) || []);
			handlers.push(handler);
			all.set(type, handlers);
		},

		/**
		 * Remove an event handler for the given type.
		 *
		 * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"`
		 * @param {Function} handler Handler function to remove
		 * @memberOf mitt
		 */
		off(type: EventType, handler: Handler) {
			if (all.has(type)) {
				all.get(type).splice(all.get(type).indexOf(handler) >>> 0, 1);
			}
		},

		/**
		 * 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: EventType, evt: any) {
			((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); });
			((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); });
		}
	};
}