Node.js Event Driven Applications - 401-advanced-javascript-davetrost/alchemy-fsjs-fall-2019 GitHub Wiki

Event Driven Applications

Reading Materials

Event Driven Programming

  • We access the EventEmitter class through the events module. const EventEmitter = require('events').EventEmitter;
  • A chat room is a good example of a domain problem where event-driven programming could be useful
    • Sample situation: alert all chat room users when a new user enters the chat
    • The chat room object is instantiated as an instance of the EventEmitter class.
      • We can reference the chat room object to set up a handler that will be triggered "on" an "event". The handler will call an "alert all users" function: chatRoomEvents.on('userJoined', alertAllUsers);
      • We can enable the chat room object to "emit" an "event". The emit function is called inside of the new user login function: chatRoomEvents.emit('userJoined', username);
  • The event emitter class also includes removeListener and removeAllListeners methods for when it is applicable.

Node Event Emitters Explained

  • All objects that emit events are members of EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.
  • An alternative to the removeListener method is to instantiate an event listener using the once() method instead of the on() method.