index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // @flow
  2. // An event handler can take an optional event argument
  3. // and should not return a value
  4. type EventHandler = (event?: any) => void;
  5. // An array of all currently registered event handlers for a type
  6. type EventHandlerList = Array<EventHandler>;
  7. // A map of event types and their corresponding event handlers.
  8. type EventHandlerMap = {
  9. [type: string]: EventHandlerList,
  10. };
  11. /** Mitt: Tiny (~200b) functional event emitter / pubsub.
  12. * @name mitt
  13. * @returns {Mitt}
  14. */
  15. export default function mitt(all: EventHandlerMap) {
  16. all = all || Object.create(null);
  17. return {
  18. /**
  19. * Register an event handler for the given type.
  20. *
  21. * @param {String} type Type of event to listen for, or `"*"` for all events
  22. * @param {Function} handler Function to call in response to given event
  23. * @memberOf mitt
  24. */
  25. on(type: string, handler: EventHandler) {
  26. (all[type] || (all[type] = [])).push(handler);
  27. },
  28. /**
  29. * Remove an event handler for the given type.
  30. *
  31. * @param {String} type Type of event to unregister `handler` from, or `"*"`
  32. * @param {Function} handler Handler function to remove
  33. * @memberOf mitt
  34. */
  35. off(type: string, handler: EventHandler) {
  36. if (all[type]) {
  37. all[type].splice(all[type].indexOf(handler) >>> 0, 1);
  38. }
  39. },
  40. /**
  41. * Invoke all handlers for the given type.
  42. * If present, `"*"` handlers are invoked after type-matched handlers.
  43. *
  44. * @param {String} type The event type to invoke
  45. * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
  46. * @memberof mitt
  47. */
  48. emit(type: string, evt: any) {
  49. (all[type] || []).map((handler) => { handler(evt); });
  50. (all['*'] || []).map((handler) => { handler(type, evt); });
  51. }
  52. };
  53. }