Skip to content

Instantly share code, notes, and snippets.

@zorbash
Created April 4, 2015 15:34
Show Gist options
  • Select an option

  • Save zorbash/d275dba3bd1537b019e6 to your computer and use it in GitHub Desktop.

Select an option

Save zorbash/d275dba3bd1537b019e6 to your computer and use it in GitHub Desktop.
A simple pubsub module
define ->
bus = (-> window.message_bus || window.message_bus = {})()
# Publish/Subscribe Functionality for classes
# @mixin
pubsub_module =
###
@param [String] topic The topic as a channel
on which to publish data
@param [*] data The data to be published
```
newspaper.publish 'new-issue', { news: 'iPhone 7 is out!' }
```
@note Code that is not OO can still publish by triggering events
on bus
@returns this
###
publish: (topic, data = null) ->
$(bus).trigger topic, data
@
###
Subscribes on a given channel/topic
@param [Object] topics The topics and their callbacks
Example:
```
person.subscribe { sleep: -> 'zzz' }
```
@returns this
###
subscribe: (topics) ->
throw new Error('invalid arguments') if $.type(topics) isnt 'object'
@_pubsub = @_pubsub || { signatures: {} }
for k, v of topics
@_pubsub.signatures[k] = @_generateSubscriptionSignature(k)
$(bus).on @_pubsub.signatures[k], (event, data) -> v.call(@, data)
@
###
@param [Array|String] topics The topics to unsubscribe from
@returns this
```
person.unsubscribe ['spam', 'soccer-news']
```
###
unsubscribe: (topics) ->
switch $.type(topics)
when 'string' then $(bus).off @_pubsub.signatures[topics]
when 'array'
$(bus).off(@_pubsub.signatures[k]) for k in topics
delete @_pubsub.signatures[k]
else throw new Error('invalid arguments')
@
###
Creates a (weak) unique (instance, topic) string to enable
instance unsubscribing from a topic without affecting the bus
###
_generateSubscriptionSignature: (topic) ->
"#{topic}.#{(Math.random() + '').slice(-8)}.#{@constructor.name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment