subscription-manager.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { addUniqueItem, removeItem } from './array.mjs';
  2. class SubscriptionManager {
  3. constructor() {
  4. this.subscriptions = [];
  5. }
  6. add(handler) {
  7. addUniqueItem(this.subscriptions, handler);
  8. return () => removeItem(this.subscriptions, handler);
  9. }
  10. notify(a, b, c) {
  11. const numSubscriptions = this.subscriptions.length;
  12. if (!numSubscriptions)
  13. return;
  14. if (numSubscriptions === 1) {
  15. /**
  16. * If there's only a single handler we can just call it without invoking a loop.
  17. */
  18. this.subscriptions[0](a, b, c);
  19. }
  20. else {
  21. for (let i = 0; i < numSubscriptions; i++) {
  22. /**
  23. * Check whether the handler exists before firing as it's possible
  24. * the subscriptions were modified during this loop running.
  25. */
  26. const handler = this.subscriptions[i];
  27. handler && handler(a, b, c);
  28. }
  29. }
  30. }
  31. getSize() {
  32. return this.subscriptions.length;
  33. }
  34. clear() {
  35. this.subscriptions.length = 0;
  36. }
  37. }
  38. export { SubscriptionManager };