Node.js / Node.js Event-Driven Programming
Creating and Handling Custom Events
In this tutorial, you'll learn to create custom events using Node.js's EventEmitter class. You'll also learn to handle these events effectively.
Section overview
5 resourcesExplores the event-driven architecture and the EventEmitter class in Node.js.
Creating and Handling Custom Events
1. Introduction
This tutorial aims to teach you how to create custom events using Node.js's EventEmitter class and how to handle these events effectively.
By the end of this tutorial, you'll learn:
- How to create custom events
- How to emit custom events
- How to handle custom events
Prerequisites: Basic knowledge of Node.js and JavaScript is required.
2. Step-by-Step Guide
Node.js's EventEmitter class allows you to create and handle custom events. You can require it and create an instance of the EventEmitter class to use it.
Creating Custom Events
To create a custom event, you use the .on() method of the EventEmitter instance. This method takes two arguments: the name of the event (a string) and a callback function to be called when the event is emitted.
Emitting Custom Events
To emit a custom event, you use the .emit() method of the EventEmitter instance. This method takes the name of the event as its first argument and any data you want to pass to the event handler as subsequent arguments.
Handling Custom Events
The callback function you passed to the .on() method is the event handler. This function is called whenever the event is emitted, and it receives the data passed to the .emit() method as its arguments.
3. Code Examples
Example 1
// Require the EventEmitter class
const EventEmitter = require('events');
// Create an instance of the EventEmitter class
const myEmitter = new EventEmitter();
// Create a custom event
myEmitter.on('sayHello', (name) => {
console.log(`Hello, ${name}!`);
});
// Emit the custom event
myEmitter.emit('sayHello', 'Alice');
In this example, we create a custom event named 'sayHello'. When this event is emitted, it logs a greeting to the console. We then emit the 'sayHello' event with the name 'Alice', so it logs 'Hello, Alice!'.
Example 2
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// Create a custom event with multiple arguments
myEmitter.on('sum', (a, b) => {
console.log(`The sum of ${a} and ${b} is ${a+b}`);
});
// Emit the custom event
myEmitter.emit('sum', 5, 3);
In this example, the 'sum' event takes two arguments and logs their sum. We emit the 'sum' event with the numbers 5 and 3, so it logs 'The sum of 5 and 3 is 8'.
4. Summary
In this tutorial, we've learned:
- How to create custom events using the
.on()method of an EventEmitter instance - How to emit custom events using the
.emit()method of an EventEmitter instance - How to handle custom events using callback functions
Next, you might want to learn about error handling in Node.js, or how to use streams and buffers.
5. Practice Exercises
- Create a custom event that logs the product of two numbers. Emit this event with the numbers 3 and 4.
- Create a custom event that logs a greeting. This event should take one argument: the name of the person to greet. Emit this event with your name.
- Create a custom event that logs a message. This event should take two arguments: a string and a number. The string is a message, and the number is the number of times to log the message. Emit this event with a message of your choice and the number 5.
Solutions
- Here's how you could solve the first exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('multiply', (a, b) => {
console.log(`The product of ${a} and ${b} is ${a*b}`);
});
myEmitter.emit('multiply', 3, 4);
- Here's a solution for the second exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
myEmitter.emit('greet', 'Your name');
- Here's a solution for the third exercise:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('repeat', (message, times) => {
for (let i = 0; i < times; i++) {
console.log(message);
}
});
myEmitter.emit('repeat', 'This is my message.', 5);
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article