Last active
October 31, 2015 21:04
-
-
Save gbuesing/b1dae47c4317a568ddae to your computer and use it in GitHub Desktop.
PubSub via jQuery without DOM bindings
This file contains 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 global PubSub system built around $.Callbacks | |
# Enables PubSub without relying on DOM element bindings | |
# | |
# Usage: | |
# | |
# PubSub.subscribe 'foo', (message) -> console.log("Received: #{message}") | |
# PubSub.publish 'foo', 'bar' | |
# # Outputs: "Received: bar" | |
$(document).on 'ready', () -> | |
window.PubSub = | |
subscriptions: {} | |
subscribe: (eventName, callbackFn) -> | |
@subscriptions[eventName] ?= $.Callbacks() | |
@subscriptions[eventName].add(callbackFn) | |
console.log("Subscribing to #{eventName}") | |
unsubscribe: (eventName, callbackFn) -> | |
@subscriptions[eventName]?.remove(callbackFn) | |
console.log("Unsubscribing to #{eventName}") | |
publish: (eventName, args) -> | |
@subscriptions[eventName]?.fire(args) | |
console.log("Publishing #{eventName}") | |
reset: () -> | |
@subscriptions = {} | |
console.log('PubSub subscriptions reset') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment