Code coverage report for js/hub.tsx

# All files / js hub.tsx

20% Statements 4/20
0% Branches 0/6
20% Functions 1/5
20% Lines 4/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67

    1x
    1x

    1x

    1x
     import { LektorEvent } from "./events";

    class Hub {
      _subscriptions: Map<string, Set<(e: any) => void>>;

      constructor() {
        this._subscriptions = new Map();
      }

      /**
       * Subscribes a callback to an event.
       */
      subscribe<T extends LektorEvent>(
        event: T,
        callback: (e: InstanceType<T>) => void
      ) {
        const eventType = event.getEventType();
        let subs = this._subscriptions.get(eventType);
        if (subs === undefined) {
          subs = new Set();
          this._subscriptions.set(eventType, subs);
        }
        subs.add(callback);
      }

      /**
       * Unsubscribes a callback from an event.
       */
      unsubscribe<T extends LektorEvent>(
        event: T,
        callback: (e: InstanceType<T>) => void
      ) {
        const eventType = event.getEventType();
        const subs = this._subscriptions.get(eventType);
        if (subs !== undefined) {
          subs.delete(callback);
        }
      }

      /**
       * Emits an event with some parameters.
       */
      emit(event: InstanceType<LektorEvent>) {
        const subs = this._subscriptions.get(event.type);
        if (subs !== undefined) {
          subs.forEach((callback) => {
            try {
              callback(event);
            } catch (e) {
              console.log(
                "Event callback failed: ",
                e,
                "callback=",
                callback,
                "event=",
                event
              );
            }
          });
        }
      }
    }

    const hub = new Hub();

    export default hub;