Skip to content

Instantly share code, notes, and snippets.

@rjz rjz/
Created Jul 12, 2012

What would you like to do?
Coffeescript pub/sub mediator
# Very simple Mediator in Coffeescript
# Based on the Pub/Sub implementation by rpflorence (
class Mediator
constructor: ->
@channels = {}
subscribe: (name, callback) ->
@channels[name] = [] unless @channels[name]?
@channels[name].push context: @, callback: callback
unsubscribe: (name, callback) ->
for sub, i in @channels[name]
@channels[name].splice(i, 1) if sub.callback == callback
publish: (name, data...) ->
for sub in @channels[name]
sub.callback.apply(sub.context, data)
# Jasmine specs
describe 'Mediator', ->
data = null
handler = null
mediator = null
beforeEach ->
data = content: 'foobar'
mediator = new Mediator
handler = jasmine.createSpy()
it 'subscribes and publishes', ->
mediator.subscribe 'channel', handler
mediator.publish 'channel', data
it 'handles unsubscribe', ->
mediator.subscribe 'channel', handler
mediator.unsubscribe 'channel', handler
mediator.publish 'channel', data

This comment has been minimized.

Copy link

commented Apr 7, 2014

Hello, great and simple code. Do I need a license to use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.