Skip to content

Instantly share code, notes, and snippets.

@robinpokorny
Last active September 4, 2022 17:27
Show Gist options
  • Save robinpokorny/d743ed9e0bc5214f79076a16c8e44a8f to your computer and use it in GitHub Desktop.
Save robinpokorny/d743ed9e0bc5214f79076a16c8e44a8f to your computer and use it in GitHub Desktop.
📰 Dead simple tweetable JavaScript PubSub pattern module using Set (ES2015)
export default () => {
const subscribers = new Set()
const sub = (fn) => {
subscribers.add(fn)
return () => subscribers.delete(fn)
}
const pub = (data) => subscribers.forEach((fn) => fn(data))
return Object.freeze({ pub, sub })
}
// Minified (by hand), 105 bytes
export default s=>(s=new Set,Object.freeze({pub:d=>s.forEach(f=>f(d)),sub:f=>s.add(f).delete.bind(s,f)}))
import pubsub from './pubsub'
// Create a new PubSub
const events = pubsub()
// Register first subscriber
// Save the unsubscribe callback
const unSubOne = events.sub((a) => console.log('one: ' + a))
const two = (a) => console.log('two: ' + a)
// Register second subscriber
const unSubTwo = events.sub(two)
// Subscriber can be registred only once, the following has no effect
events.sub(two)
// Dispatch a string
// `two` is called just once
events.pub('foo')
// "one: foo"
// "two: foo"
// Deregister a subscriber
// Returns true if the function has been removed successfully
unSubOne() // true
// Dispatch a string
// `one` is not called
events.pub('bar')
// "two: bar"
@robinpokorny
Copy link
Author

Oh, the very minimal version would be 91 characters:

export default (s=new Set)=>({pub:d=>s.forEach(f=>f(d)),sub:f=>s.add(f).delete.bind(s,f)})

That is removing Object.freeze. I would not recommend using that one though…

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