Created
March 31, 2017 20:15
-
-
Save wesvetter/e14e16e2ec04bf32bb835bab55ebe632 to your computer and use it in GitHub Desktop.
A simple PubSub implementation in CoffeeScript
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
# 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