aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/events-proxy.js
blob: d1199a27852bd7f52e5d61f2ef13c3c8143f79a5 (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
module.exports = function createEventEmitterProxy(eventEmitter, listeners) {
  let target = eventEmitter
  const eventHandlers = listeners || {}
  const proxy = new Proxy({}, {
    get: (obj, name) => {
      // intercept listeners
      if (name === 'on') return addListener
      if (name === 'setTarget') return setTarget
      if (name === 'proxyEventHandlers') return eventHandlers
      return target[name]
    },
    set: (obj, name, value) => {
      target[name] = value
      return true
    },
  })
  function setTarget (eventEmitter) {
    target = eventEmitter
    // migrate listeners
    Object.keys(eventHandlers).forEach((name) => {
      eventHandlers[name].forEach((handler) => target.on(name, 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
}