mitt.es.js 1.8 KB

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