Skip to content

Instantly share code, notes, and snippets.

@jimbolla
Created November 16, 2015 19:38
Show Gist options
  • Save jimbolla/f548d20da071b7c67807 to your computer and use it in GitHub Desktop.
Save jimbolla/f548d20da071b7c67807 to your computer and use it in GitHub Desktop.
protectFromUnmount
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;
}
@Dottenpixel
Copy link

This is great. Tagging this with the GitHub issue that brought me here.

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