Skip to content

Instantly share code, notes, and snippets.

@rjz rjz/mediator.coffee
Created Jul 12, 2012

Embed
What would you like to do?
Coffeescript pub/sub mediator
# Very simple Mediator in Coffeescript
# Based on the Pub/Sub implementation by rpflorence (https://github.com/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
expect(handler).toHaveBeenCalledWith(data)
it 'handles unsubscribe', ->
mediator.subscribe 'channel', handler
mediator.unsubscribe 'channel', handler
mediator.publish 'channel', data
expect(handler).not.toHaveBeenCalled()
@Yuripetusko

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.