Skip to content

Instantly share code, notes, and snippets.

@gbuesing
Last active October 31, 2015 21:04
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 gbuesing/b1dae47c4317a568ddae to your computer and use it in GitHub Desktop.
Save gbuesing/b1dae47c4317a568ddae to your computer and use it in GitHub Desktop.
PubSub via jQuery without DOM bindings
# 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