EventEmitter.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.EventEmitter = void 0;
  7. /**
  8. * Copyright 2022 Google LLC.
  9. * Copyright (c) Microsoft Corporation.
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. const mitt_1 = __importDefault(require("mitt"));
  24. class EventEmitter {
  25. #emitter = (0, mitt_1.default)();
  26. on(type, handler) {
  27. this.#emitter.on(type, handler);
  28. return this;
  29. }
  30. /**
  31. * Like `on` but the listener will only be fired once and then it will be removed.
  32. * @param event The event you'd like to listen to
  33. * @param handler The handler function to run when the event occurs
  34. * @return `this` to enable chaining method calls.
  35. */
  36. once(event, handler) {
  37. const onceHandler = (eventData) => {
  38. handler(eventData);
  39. this.off(event, onceHandler);
  40. };
  41. return this.on(event, onceHandler);
  42. }
  43. off(type, handler) {
  44. this.#emitter.off(type, handler);
  45. return this;
  46. }
  47. /**
  48. * Emits an event and call any associated listeners.
  49. *
  50. * @param event The event to emit.
  51. * @param eventData Any data to emit with the event.
  52. * @return `true` if there are any listeners, `false` otherwise.
  53. */
  54. emit(event, eventData) {
  55. this.#emitter.emit(event, eventData);
  56. }
  57. }
  58. exports.EventEmitter = EventEmitter;
  59. //# sourceMappingURL=EventEmitter.js.map