mitt.ts 2.1 KB

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