mitt.js 955 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { defaultTo } from "./helpers";
  2. export function mitt(events) {
  3. const _events = defaultTo(events, new Map());
  4. return {
  5. events: _events,
  6. on(topic, handler) {
  7. const handlers = _events.get(topic);
  8. if (handlers) {
  9. handlers.push(handler);
  10. } else {
  11. _events.set(topic, [handler]);
  12. }
  13. },
  14. off(topic, handler) {
  15. const handlers = _events.get(topic);
  16. if (handlers) {
  17. if (handler) {
  18. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  19. } else {
  20. _events.set(topic, []);
  21. }
  22. }
  23. },
  24. emit(topic, event) {
  25. const handlers = _events.get(topic);
  26. if (handlers) {
  27. for (const handler of handlers.slice()) {
  28. handler(event);
  29. }
  30. }
  31. const hdlrs = _events.get("*");
  32. if (hdlrs) {
  33. for (const handler of hdlrs.slice()) {
  34. handler(topic, event);
  35. }
  36. }
  37. }
  38. };
  39. }