WorkboxEventTarget.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2019 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. /**
  8. * A minimal `EventTarget` shim.
  9. * This is necessary because not all browsers support constructable
  10. * `EventTarget`, so using a real `EventTarget` will error.
  11. * @private
  12. */
  13. export class WorkboxEventTarget {
  14. constructor() {
  15. this._eventListenerRegistry = new Map();
  16. }
  17. /**
  18. * @param {string} type
  19. * @param {Function} listener
  20. * @private
  21. */
  22. addEventListener(type, listener) {
  23. const foo = this._getEventListenersByType(type);
  24. foo.add(listener);
  25. }
  26. /**
  27. * @param {string} type
  28. * @param {Function} listener
  29. * @private
  30. */
  31. removeEventListener(type, listener) {
  32. this._getEventListenersByType(type).delete(listener);
  33. }
  34. /**
  35. * @param {Object} event
  36. * @private
  37. */
  38. dispatchEvent(event) {
  39. event.target = this;
  40. const listeners = this._getEventListenersByType(event.type);
  41. for (const listener of listeners) {
  42. listener(event);
  43. }
  44. }
  45. /**
  46. * Returns a Set of listeners associated with the passed event type.
  47. * If no handlers have been registered, an empty Set is returned.
  48. *
  49. * @param {string} type The event type.
  50. * @return {Set<ListenerCallback>} An array of handler functions.
  51. * @private
  52. */
  53. _getEventListenersByType(type) {
  54. if (!this._eventListenerRegistry.has(type)) {
  55. this._eventListenerRegistry.set(type, new Set());
  56. }
  57. return this._eventListenerRegistry.get(type);
  58. }
  59. }