Skip to content

Instantly share code, notes, and snippets.

@rjz
Created July 12, 2012 17:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjz/3099426 to your computer and use it in GitHub Desktop.
Save rjz/3099426 to your computer and use it in GitHub Desktop.
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
Copy link

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