Created
July 12, 2012 17:14
-
-
Save rjz/3099426 to your computer and use it in GitHub Desktop.
Coffeescript pub/sub mediator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, great and simple code. Do I need a license to use this?