Created
September 21, 2017 16:00
-
-
Save atticoos/e08beab2e75317ecc40764cba43ebba4 to your computer and use it in GitHub Desktop.
Allows passing a callback serially between two systems
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
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
callback called with hello 123 world