aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/events-proxy.js
blob: f83773ccc37d937414d16ca8b678ee99207f1bbc (plain) (blame)
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
/**
 * Returns an EventEmitter that proxies events from the given event emitter
 * @param {any} eventEmitter
 * @param {object} listeners - The listeners to proxy to
 * @returns {any}
 */
module.exports = function createEventEmitterProxy (eventEmitter, listeners) {
  let target = eventEmitter
  const eventHandlers = listeners || {}
  const proxy = /** @type {any} */ (new Proxy({}, {
    get: (_, name) => {
      // intercept listeners
      if (name === 'on') return addListener
      if (name === 'setTarget') return setTarget
      if (name === 'proxyEventHandlers') return eventHandlers
      return (/** @type {any} */ (target))[name]
    },
    set: (_, name, value) => {
      target[name] = value
      return true
    },
  }))
  function setTarget (/** @type {EventEmitter} */ eventEmitter) {
    target = eventEmitter
    // migrate listeners
    Object.keys(eventHandlers).forEach((name) => {
      /** @type {Array<Function>} */ (eventHandlers[name]).forEach((handler) => target.on(name, handler))
    })
  }
  /**
   * Attaches a function to be called whenever the specified event is emitted
   * @param {string} name
   * @param {Function} handler
   */
  function addListener (name, handler) {
    if (!eventHandlers[name]) eventHandlers[name] = []
    eventHandlers[name].push(handler)
    target.on(name, handler)
  }
  if (listeners) proxy.setTarget(eventEmitter)
  return proxy
}