1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/lib/events-proxy.js

31 lines
923 B
JavaScript
Raw Normal View History

2017-10-11 02:15:14 +02:00
module.exports = function createEventEmitterProxy(eventEmitter, eventHandlers = {}) {
2017-09-26 20:52:57 +02:00
let target = eventEmitter
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
},
})
2017-10-11 02:15:14 +02:00
proxy.setTarget(eventEmitter)
return proxy
2017-09-26 20:52:57 +02:00
function setTarget (eventEmitter) {
target = eventEmitter
2017-10-11 02:15:14 +02:00
// migrate eventHandlers
2017-09-26 20:52:57 +02:00
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)
}
}