dispatcher.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.Dispatcher = void 0;
  13. class Dispatcher {
  14. constructor(targets) {
  15. this.targets = targets;
  16. }
  17. callTargets(targets, methodName, ...args) {
  18. return targets.map(target => {
  19. const method = target[methodName];
  20. if (method && typeof method === 'function') {
  21. return method.apply(target, args);
  22. }
  23. });
  24. }
  25. invokeHookAsync(methodName, ...args) {
  26. return __awaiter(this, void 0, void 0, function* () {
  27. return yield Promise.all(this.callTargets(this.targets, methodName, ...args));
  28. });
  29. }
  30. invokeHookSync(methodName, ...args) {
  31. return this.callTargets(this.targets, methodName, ...args);
  32. }
  33. reverseInvokeHookSync(methodName, ...args) {
  34. return this.callTargets(this.targets.reverse(), methodName, ...args);
  35. }
  36. invokeHooksUntilNonNull(methodName, ...args) {
  37. return __awaiter(this, void 0, void 0, function* () {
  38. for (const target of this.targets) {
  39. const method = target[methodName];
  40. if (!(method && typeof method === 'function')) {
  41. continue;
  42. }
  43. const value = yield method.apply(target, args);
  44. if (value !== null) {
  45. return value;
  46. }
  47. }
  48. return null;
  49. });
  50. }
  51. invokeDidStartHook(methodName, ...args) {
  52. const didEndHooks = [];
  53. for (const target of this.targets) {
  54. const method = target[methodName];
  55. if (method && typeof method === 'function') {
  56. const didEndHook = method.apply(target, args);
  57. if (didEndHook) {
  58. didEndHooks.push(didEndHook);
  59. }
  60. }
  61. }
  62. return (...args) => {
  63. didEndHooks.reverse();
  64. for (const didEndHook of didEndHooks) {
  65. didEndHook(...args);
  66. }
  67. };
  68. }
  69. }
  70. exports.Dispatcher = Dispatcher;
  71. //# sourceMappingURL=dispatcher.js.map