DEV Community

Cover image for Understanding EventEmitter - Nodejs Core Concept
Taiwo Shobo
Taiwo Shobo

Posted on

Understanding EventEmitter - Nodejs Core Concept

Introduction

Prerequisites

What is an Event Emitter?

Why use Event Emitters?

Event Emitter vs Callback

Implementing Event Emitters

Conclusion

Introduction

An event emitter is a powerful object used for inter-component communication within an application. It operates by emitting events, which are named signals that can be observed and handled by other parts of the code.

Event emitters are objects that can send messages to other objects, informing them about something that has happened. Developers can use event emitters to write code that responds to events without the need to check for them. However, event emitters do this by emitting events, creating named signals that other objects can listen to and handle.

JavaScript's event-driven structure lets us run code when events occur using event handlers. Node.js uses this feature.

In this article, we'll discuss what event emitters are, why event emitters, and implementing event emitters. Let's get started!

Prerequisites

  • Basic knowledge of Javascript and ES6 syntax
  • Installation of Nodejs on your system

What is an Event Emitter?

At its core, an event emitter is a communication channel within your JavaScript code. Think of it as a messenger whose role is to ease the seamless interaction of different code components. It enables you to declare, "When this specific event occurs, notify everyone."

Popular Javascript frameworks use Event emitters such as Node.js, React, and Vue.js. This makes them a valuable skill to have for any JavaScript developer.

Why use Event Emitters?

Node.js uses a special class called EventEmitter to bring exciting event-driven programming to the backend. This class is a part of the core module in Node.js. Event emitters and listeners play a vital role in Node.js. They help Node.js do its job with its single-threaded, asynchronous, nonblocking I/O feature.

Event Emitter vs Callback

Callbacks are a good way to handle asynchronous operations, but they can get messy when you have a lot of events to deal with. Event emitters solve this problem by letting you create a central hub for event handling.

This hub, called an event emitter, can listen for events from anywhere in your application and then send them to the right place. This makes it easy to keep your code organized and reusable.

Furthermore, event emitters offer greater flexibility compared to callbacks. You can create various types of events, such as responding to a user's button click, receiving a new message, or signaling task completion.

Implementing Event Emitters

Creating an Event Emitter

We'll look at the two most typical methods for building an event emitter in Node.js. We can:

  1. Use an event emitter object directly
  2. Create an object that extends the event emitter object.

To create an event emitter in JavaScript, you can use the built-in EventEmitter class in Node.js.

Let's start by making a folder to keep all our code. Open your terminal and create a folder named event-emitters:

mkdir event-emitters
Enter fullscreen mode Exit fullscreen mode

Enter the folder:

cd event-emitters
Enter fullscreen mode Exit fullscreen mode

Create a file:

touch personEmitter.js
Enter fullscreen mode Exit fullscreen mode

Code Example - Using the event emitter object directly

const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Enter fullscreen mode Exit fullscreen mode

Code example - Using object that extends the event emitter object

const EventEmitter = require('events')

class Person extends EventEmitter{}

// Instantiating the object with new keyword
const person = new Person()
Enter fullscreen mode Exit fullscreen mode

Adding Event Listener

Event listeners are functions that you register to respond to specific events. You can add event listeners using the on() method or the addListener() method.

Node.js offers an alternative to using the on() method in this particular scenario through the once() function.

Just like on(), the once() function requires the event name as its first parameter and activates a callback function when the event triggers. When an event gets emitted, and a listener is once(), Node.js eliminates the listener and performs the code within the callback function.

This function waits for a specific event name to trigger and executes a callback when the event occurs. When adding a listener, you follow this process:

eventEmitter.on(event_name, callback_function) {
    action
}

person.on('get', () => console.log('I greeted you this morning Shobo'))

person.once('get', () => console.log('This event get fired once'))

Enter fullscreen mode Exit fullscreen mode

Emitting Events

To trigger an event, you use the emit() method. All listeners registered for that event type will be executed in the order they were added.

You should provide the event's name as a string, and after specifying the event name, you can add any number of arguments.

Now run this script with node:

node personEmitter.js
Enter fullscreen mode Exit fullscreen mode
person.emit('get')
// Output:
// I greeted you this morning Shobo
Enter fullscreen mode Exit fullscreen mode

Removing Event Listeners

You can remove event listeners using the off() method and removeListener() method. This is useful when you no longer want a listener to respond to events.

The off() method and the removeListener() method accepts two arguments: the event name and the function that’s listening to it.

const offPerson = () => {
  console.log('Am cutting you off')
}

person.removeListener('get', offPerson)

Enter fullscreen mode Exit fullscreen mode

Handling Errors and Exceptions

If an event emitter cannot perform an action, it must emit an event to signify that the attempt has failed. The error event must have its name set to "error," and it must be accompanied by an Error object. When working with event emitters, it's essential to handle errors effectively. You can use the error event to capture and handle exceptions thrown by listeners.

person.on('error', (error) => {
  console.error('An error occurred:', error);
});

person.emit('error', new Error('Something went wrong.'));

Enter fullscreen mode Exit fullscreen mode

Conclusion

You discovered how to start events with Node.js event emitters in this lesson. To run code each time an event is triggered, you first publish events using the emit() method of an EventEmitter object, then listen to events using the on() procedures.

We covered the fundamentals of event emitters in JavaScript. Event emitters are a powerful tool for building responsive and scalable applications, and mastering them will enhance your development skills.

Watch for the next article that will be released shortly on Event Emitter. You will be building a sales ticket management, and with this, you will delve deeper into the world of event-driven programming and enhance your development skills.

Top comments (1)

Collapse
 
frankeze profile image
Frank

Awesome post, very insightful 👍