Last active
May 1, 2017 00:37
-
-
Save jdjkelly/25077fa1e89142bda41b3fe20d4da096 to your computer and use it in GitHub Desktop.
subscribe
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
let currentListeners = [] | |
let nextListeners = currentListeners | |
... | |
function subscribe(listener) { | |
if (typeof listener !== 'function') { | |
throw new Error('Expected listener to be a function.') | |
} | |
let isSubscribed = true | |
ensureCanMutateNextListeners() | |
nextListeners.push(listener) | |
return function unsubscribe() { | |
if (!isSubscribed) { | |
return | |
} | |
isSubscribed = false | |
ensureCanMutateNextListeners() | |
const index = nextListeners.indexOf(listener) | |
nextListeners.splice(index, 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment