Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Last active August 12, 2020 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/82ef736f27e37bde171b9d1125691a76 to your computer and use it in GitHub Desktop.
Save aleclarson/82ef736f27e37bde171b9d1125691a76 to your computer and use it in GitHub Desktop.
import {expectOple} from 'ople'
// Note: Unique function values are expected.
export function forwardListeners(listenFns) {
const disposeFns = new Map()
const self = expectOple()
hookBefore(self, {
_addListener(key, fn) {
if (!listenFns[key]) return
disposeFns.set(fn, listenFns[key](fn))
},
_removeListener(key, fn) {
if (!listenFns[key]) return
disposeFns.get(key)()
},
})
}
function hookBefore(self, hooks) {
for (const name in fns) {
const orig = self[name]
self[name] = (...args) => {
hooks[name].apply(self, args)
orig.apply(self, args)
}
}
}
export const listen = (source, type) => (fn) => {
source.on(type, fn)
return () => source.off(type, fn)
}
//
// DEMO
//
const api = new Ople()
const demo = new Ople(self => {
forwardListeners({
test: listen(api, 'test'),
})
})
demo.on('test', console.log)
// Emits from either are logged.
api.emit('test', 'hello')
demo.emit('test', 'world')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment