block by joyrexus 9007874

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

index.coffee