Skip to content

Instantly share code, notes, and snippets.

@gbuesing
Last active Oct 31, 2015
Embed
What would you like to do?
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