Skip to content

Instantly share code, notes, and snippets.

@atticoos
Created September 21, 2017 16:00
Show Gist options
  • Save atticoos/e08beab2e75317ecc40764cba43ebba4 to your computer and use it in GitHub Desktop.
Save atticoos/e08beab2e75317ecc40764cba43ebba4 to your computer and use it in GitHub Desktop.
Allows passing a callback serially between two systems
var seed = 0;
var callbacks = new Map();
function registerCallback (cb) {
if (callbacks.has(cb)) {
return callbacks.get(cb)
}
var id = ++seed;
callbacks.set(cb, id)
callbacks.set(id, cb)
return id;
}
function createSerialCallback (cbId) {
return (...args) => {
var cb = callbacks.get(cbId)
if (cb) {
cb(...args)
}
}
}
function test (...args) {
console.log('callback called with', ...args)
}
const callbackRef = registerCallback(test)
const serialCallback = createSerialCallback(callbackRef)
serialCallback('hello', 123, 'world')
@atticoos
Copy link
Author

Output: callback called with hello 123 world

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment