Event Driven Programming in Node.js - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki

Node.js natively provides us with a useful module called EventEmitter that allows us to get started incorporating Event-Driven Programming in our project right away.

  • We access the EventEmitter class through the events module. Once imported we’ll need to create a new object from the class to start using it. const EventEmitter = require('events').EventEmitter; const myEventEmitter = new EventEmitter;
  • We’ll need an event listener for a userJoined event. First, we’ll write a function that will act as our event listener, then we can use EventEmitters on method to set the listener. const EventEmitter = require('events').EventEmitter; const chatRoomEvents = new EventEmitter;

function userJoined(username){ // Assuming we already have a function to alert all users. alertAllUsers('User ' + username + ' has joined the chat.'); }

// Run the userJoined function when a 'userJoined' event is triggered. chatRoomEvents.on('userJoined', userJoined);

  • EventEmitter has an emit method that we we use to trigger the event. function login(username){ chatRoomEvents.emit('userJoined', username); }
  • To remove event listeners in EventEmitter we can use the removeListener or removeAllListeners method. const EventEmitter = require('events').EventEmitter; const chatRoomEvents = new EventEmitter;

function userJoined(username){ chatRoomEvents.on('message', function(message){ document.write(message); }) }

chatRoomEvents.on('userJoined', userJoined);

  • All of that headache can be avoided if we rewrite the code like so: const EventEmitter = require('events').EventEmitter; const chatRoomEvents = new EventEmitter;

function displayMessage(message){ document.write(message); }

function userJoined(username){ chatRoomEvents.on('message', displayMessage); }

chatRoomEvents.on('userJoined', userJoined); Now if we want to remove the displayMessage function from the message event’s list of handlers: chatRoomEvents.removeListener('message', displayMessage);

  • We might have a sendMail function that delivers our mail to a server. We might also have a receiveMail function that tells the server to deliver us any new mail it has for us. We’ll call the object responsible for these server interactions our Mailbox. const Mailbox = { sendMail: function(){ // code to send mail. }, receiveMail: function(){ // check server for new mail. } } const EventEmitter = require('events').EventEmitter; const myGatorEvents = new EventEmitter;

class Food { constructor(name) { this.name = name; // Become eaten when gator emits 'gatorEat' myGatorEvents.on('gatorEat', this.becomeEaten); }

becomeEaten(){ return 'I have been eaten.'; } }

var bacon = new Food('bacon');

const gator = { eat() { myGatorEvents.emit('gatorEat'); } }