mitt.es.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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] || []).slice().map(function (handler) { handler(evt); });
  45. (all['*'] || []).slice().map(function (handler) { handler(type, evt); });
  46. }
  47. };
  48. }
  49. export default mitt;
  50. //# sourceMappingURL=mitt.es.js.map