Skip to content

Instantly share code, notes, and snippets.

@jimbolla
Created November 16, 2015 19:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
}
@istarkov
Copy link

What the idea of this raceSafeCallbacks
What the situation you will need them?

This is enough

function protectFromUnmount() {
    let hasUnmounted_ = false;

    const protect = (callback) => {
        return (...args) => !hasUnmounted_ && callback(...args);
    };

    protect.unmount = () => hasUnmounted_ = true;

    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