Last active
August 12, 2020 15:34
-
-
Save aleclarson/82ef736f27e37bde171b9d1125691a76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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