Skip to content

Instantly share code, notes, and snippets.

@wesvetter
Created March 31, 2017 20:15
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 wesvetter/e14e16e2ec04bf32bb835bab55ebe632 to your computer and use it in GitHub Desktop.
Save wesvetter/e14e16e2ec04bf32bb835bab55ebe632 to your computer and use it in GitHub Desktop.
A simple PubSub implementation in CoffeeScript
# Simple PubSub implementation
tinysub = do (lib={}) ->
# Storage for topics that can be broadcast or listened to.
topics = {}
# Used to generate subscriber tokens
subscriber_uid = -1
generate_token = -> (++subscriber_uid).toString()
# Publish or broadcast events of interest with a specific topic name and
# arguments such as the data to pass along.
lib.publish = (topic, args) ->
subscribers = topics[topic]
return false unless subscribers?.length
sub.func(topic, args) for sub in subscribers
this
# Subscribe to events of interest with a specific topic name and a callback
# function, to be executed when the topic/event is observed.
lib.subscribe = (topic, func) ->
topics[topic] = [] if not topics[topic]
token = generate_token()
topics[topic].push(token: token, func: func)
token
# Unsubscribe from a specific topic, based on a tokenized reference to the
# subscription.
lib.unsubscribe = (token) ->
for topic, subscribers of topics when subscribers?
for sub, index in subscribers
token[topic] = subscribers.splice(index,1) # Remove the subscriber
this
lib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment