Created
November 16, 2015 19:38
-
-
Save jimbolla/f548d20da071b7c67807 to your computer and use it in GitHub Desktop.
protectFromUnmount
This file contains 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
function protectFromUnmount() { | |
let callbacks = {}; | |
let count = 0; | |
const noop = value => value; | |
const wrapCallback = id => function(...params) { | |
const raceSafeCallbacks = callbacks; | |
if (!raceSafeCallbacks) | |
return noop(...params); | |
const callback = raceSafeCallbacks[id]; | |
delete raceSafeCallbacks[id]; | |
return callback(...params); | |
}; | |
const protect = (callback) => { | |
const raceSafeCallbacks = callbacks; | |
if (!raceSafeCallbacks) | |
return noop; | |
const id = count++; | |
raceSafeCallbacks[id] = callback; | |
return wrapCallback(id); | |
}; | |
protect.unmount = () => callbacks = null; | |
return protect; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What the idea of this raceSafeCallbacks
What the situation you will need them?
This is enough