Content:
**1.Introduction about events in node.js
2.Example of using events in node.js
1.Introduction about events in node.js**
1.1.EventEmitter class and events inbuilt module provided by node.js
Events inbuilt module in node.js contains an EventEmitter class, that can be extended by other classes to use many of its methods. EventEmitter class calls two methods to add and remove events.
1.2.EventEmitter class methods
EventEmitter class has a method called "on" that takes in the name of the event as the first argument and the event callback function as the second argument.
The event callback function:
function syntax: when "this" is an argument it refers to the EventEmitter instance
arrow syntax: when "this" is an argument it refers to an empty object
EventEmitter class has a method called "emit" that takes in the name of the event to fire or trigger as the first argument and the following parameters as arguments to the callback function.
2.
The eventemitter class: examples
const {EventEmitter} = require("events");
class EventEmitterClass extends EventEmitter {
constructor() {
super();
}
}
module.exports = {EventEmitterClass};
Set of examples to use the eventemitter class:
const {EventEmitterClass} = require("./eventEmitter");
const myEmitter = new EventEmitterClass();
myEmitter.on('event', (a, b) => {
console.log(a,b);
setImmediate(() => {
console.log('this happens asynchronously');
});
});
myEmitter.emit('event', 'a', 'b');
let m = 0;
myEmitter.once('event', () => {
console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
myEmitter.emit('error', new Error('whoops!'));
EventEmitterClass.captureRejections = true;
const ee = new EventEmitterClass();
ee.on('something', async (value) => {
throw new Error('kaboom');
});
ee.on('error', (err) => {
console.error('whoops! there was an error');
});
ee.emit('something');
Top comments (0)