Code coverage report for js/hub.jsx

# All files / js hub.jsx

10.34% Statements 3/29
0% Branches 0/14
50% Functions 1/2
10.34% Lines 3/29

    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
    68

    1x
    1x

    1x

     'use strict'

    class Hub {
      constructor () {
        this._subscriptions = {}
      }

      /* subscribes a callback to an event */
      subscribe (event, callback) {
        if (typeof event !== 'string') {
          event = event.getEventType()
        }

        let subs = this._subscriptions[event]
        if (subs === undefined) {
          this._subscriptions[event] = subs = []
        }

        for (let i = 0; i < subs.length; i++) {
          if (subs[i] === callback) {
            return false
          }
        }

        subs.push(callback)
        return true
      }

      /* unsubscribes a callback from an event */
      unsubscribe (event, callback) {
        if (typeof event !== 'string') {
          event = event.getEventType()
        }

        const subs = this._subscriptions[event]
        if (subs === undefined) {
          return false
        }

        for (let i = 0; i < subs.length; i++) {
          if (subs[i] === callback) {
            subs.splice(i, 1)
            return true
          }
        }
        return false
      }

      /* emits an event with some parameters */
      emit (event) {
        const subs = this._subscriptions[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