Skip to content

16 Event Driven Applications

Jagdeep Singh edited this page Jun 19, 2019 · 1 revision

Node.js core API is based on asynchronouse event-driven architecture in which certain kind of objects called emitters periodically emit events that cause listener objects to be called.

When the EventEmitter obbject emits an event, all the functions attached to that specific event are called synchronously. All values returned by the called listeners are ignored and will be discarded.

Asynchronous

By default, all listeners attached to a particular event object are called by the EventListener object synchronously in the order in which they are registered or attached to the event object. If we want to break that flow and switch to asynchronous mode then we can use setImmediate() or process.nextTick() methods:

  • The nextTick is called in the iteration after the task of displaying 1st log statement is executed and then in the next cycle of picking up event from event loop task defined in process.nextTick() is called while setImmediate allows runnign some task asynchronously.

Handling event calls in Node.js:

The listener can be invoked only once using eventEmitter.once() method while every time the event is emitted using eventEmitter.on() method:

const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const myEmitter2 = new MyEmitter();

let m = 0, n = 0;
myEmitter.on('event', () => {
  console.log("M value:", ++m);
});
myEmitter.emit('emit');
myEmitter.emit('event');

myEmitter2.once('event', () => {
  console.log("N value:",++n);
});
myEmitter2.emit('event');
// Prints: 1
myEmitter2.emit('event');
//Ignored

An Event Handler is a callback function that will be called when an event is triggered.

A Main Loop listens for event triggers and calls the associated event handler for that event.

EventEmitter

The module called EventEmitter allows us to get started incorporating Event-Driven Programming.

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;

Example: Alerting everyone when a new user joins a chat room.

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);

function login(username) {
  chatRoomEvents.emit('userJoined', username);
}

Removing Listeners

To remove event listeners in EventEmitter we can use the removeListener or removeAllListeners method. For the built in EventEmitter, you must pass in a reference to the exact function you wish to remove when using the removeListener method.

Clone this wiki locally