Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created February 14, 2014 19:50
Show Gist options
  • Save joyrexus/9007874 to your computer and use it in GitHub Desktop.
Save joyrexus/9007874 to your computer and use it in GitHub Desktop.
EventEmitter demo

Quick demo of the observer / pubsub pattern.

Here we leverage node's EventEmitter class as the basis for our observable/publisher. (See this variant for a publisher class not based on EventEmitter.)

The scenario is a publisher notifiying its subscribers of events. Subscribers have callbacks (watch, read) registered with the publisher that listen for particular event types. Each subscriber's callback is called when the publisher emits the associated event.

# create instances
acme = new Pub('Acme Media')  # publisher
bob = new Sub('Bob')          # subscribers
ann = new Sub('Ann')

# set up subscriptions
acme
  .on('vogue', ann.read)
  .on('glee', ann.watch)
  .on('glee', bob.watch)

# notify subscribers
acme
  .notify('glee')
  .notify('vogue')

Expected output:

Acme Media notifies its subscribers of glee:
 * Ann is now watching GLEE
 * Bob is now watching GLEE

Acme Media notifies its subscribers of glee:
 * Ann is now reading VOGUE
EventEmitter = require('events').EventEmitter
class Pub extends EventEmitter
'''
Publisher / Observable / Event Emitter
'''
constructor: (@name) -> super()
notify: (event) ->
console.log "#{@name} notifies its subscribers of #{event}:"
@emit event, event.toUpperCase()
@
class Sub
'''
Subscriber with various listener methods.
'''
constructor: (@name) ->
watch: (show) =>
console.log " * #{@name} is now watching #{show}"
read: (magazine) =>
console.log " * #{@name} is now reading #{magazine}"
# create instances
#
# publisher
acme = new Pub('Acme Media')
#
# subscribers
joe = new Sub('Joe')
bob = new Sub('Bob')
ann = new Sub('Ann')
# set up subscriptions (register callbacks listening for specified events)
acme
.on('glee', ann.watch)
.on('glee', bob.watch)
.on('vogue', ann.read)
.on('gun & garden', bob.read)
.on('gun & garden', joe.read)
.on('sons of anarchy', bob.watch)
.on('sons of anarchy', joe.watch)
# notify subscribers
events = ['vogue', 'gun & garden', 'glee', 'sons of anarchy']
acme.notify(event) for event in events
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment