Skip to content

Instantly share code, notes, and snippets.

@jdjkelly
Last active May 1, 2017 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdjkelly/25077fa1e89142bda41b3fe20d4da096 to your computer and use it in GitHub Desktop.
Save jdjkelly/25077fa1e89142bda41b3fe20d4da096 to your computer and use it in GitHub Desktop.
subscribe
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