Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Last active January 13, 2016 15:41
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 bjoerge/1f1cc3d09efeba4d396c to your computer and use it in GitHub Desktop.
Save bjoerge/1f1cc3d09efeba4d396c to your computer and use it in GitHub Desktop.
Minimalistic pubsub

Minimalistic pubsub

function pubsubber() {
  const subscribers = []
  return {
    subscribe,
    once,
    publish
  }
  function subscribe(subscriber) {
    subscribers.push(subscriber)
    return unsubscribe.bind(null, subscriber)
  }
  function once(subscriber) {
    const unsub = subscribe((...args) => {
      subscriber(...args)
      unsub()
    })
    return unsub
  }
  function publish(...args) {
    subscribers.forEach(subscriber => subscriber(...args))
  }
  function unsubscribe(fn) {
    const idx = subscribers.indexOf(fn)
    if (idx) {
      subscribers.splice(idx, 1)
    }
  }
}

Usage:

const pubsub = pubsubber()

const unsubscribe = pubsub.subscribe(value => {
  console.log('every', value)
})

pubsub.once(value => {
  console.log('once', value)
})

pubsub.publish('Hello')
// => 'every Hello'
// => 'once Hello'

pubsub.publish('World')
// => 'every World'

unsubscribe()

pubsub.publish('Something')
// Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment