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:
Prerequisites: Basic knowledge of Node.js and JavaScript is required.
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.
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.
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.
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.
// 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!'.
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'.
In this tutorial, we've learned:
.on()
method of an EventEmitter instance.emit()
method of an EventEmitter instanceNext, you might want to learn about error handling in Node.js, or how to use streams and buffers.
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);
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
myEmitter.emit('greet', 'Your name');
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);