vben
2020-12-31 9c2f3f30bbd8abcccc4f256183ed7794da7fcda2
提交 | 用户 | age
814f9a 1 /**
V 2  * Mitt: Tiny functional event emitter / pubsub
3  *
4  * @name mitt
5  * @param {Array} [all] Optional array of event names to registered handler functions
6  * @returns {Function} The function's instance
7  */
8 export default class Mitt {
a65ad9 9   private cache: Map<string | Symbol, Array<(...data: any) => void>>;
814f9a 10   constructor(all = []) {
V 11     // A Map of event names to registered handler functions.
12     this.cache = new Map(all);
13   }
14
a65ad9 15   once(type: string | Symbol, handler: Fn) {
814f9a 16     const decor = (...args: any[]) => {
V 17       handler && handler.apply(this, args);
18       this.off(type, decor);
19     };
20     this.on(type, decor);
21     return this;
22   }
23
24   /**
25    * Register an event handler for the given type.
26    *
27    * @param {string|symbol} type Type of event to listen for, or `"*"` for all events
28    * @param {Function} handler Function to call in response to given event
29    */
a65ad9 30   on(type: string | Symbol, handler: Fn) {
814f9a 31     const handlers = this.cache.get(type);
V 32     const added = handlers && handlers.push(handler);
33     if (!added) {
34       this.cache.set(type, [handler]);
35     }
36   }
37
38   /**
39    * Remove an event handler for the given type.
40    *
41    * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"`
42    * @param {Function} handler Handler function to remove
43    */
a65ad9 44   off(type: string | Symbol, handler: Fn) {
814f9a 45     const handlers = this.cache.get(type);
V 46     if (handlers) {
47       handlers.splice(handlers.indexOf(handler) >>> 0, 1);
48     }
49   }
50
51   /**
52    * Invoke all handlers for the given type.
53    * If present, `"*"` handlers are invoked after type-matched handlers.
54    *
55    * Note: Manually firing "*" handlers is not supported.
56    *
57    * @param {string|symbol} type The event type to invoke
58    * @param {*} [evt] Any value (object is recommended and powerful), passed to each handler
59    */
a65ad9 60   emit(type: string | Symbol, evt: any) {
814f9a 61     for (const handler of (this.cache.get(type) || []).slice()) handler(evt);
V 62     for (const handler of (this.cache.get('*') || []).slice()) handler(type, evt);
63   }
64
65   /**
66    * Remove all event handlers.
67    *
68    * Note: This will also remove event handlers passed via `mitt(all: EventHandlerMap)`.
69    */
70   clear() {
71     this.cache.clear();
72   }
73 }