Tuesday, 2 October 2018

node.js: Implementing custom event emitter

By extending EventEmitter class, you can create custom event emitter.

Example
var EventEmitter = require('events').EventEmitter;
class ClockEmitter extends EventEmitter {};

Since ClockEmitter is a sub class of EventEmitter, it inherits all the functionality of EventEmitter class.

You can add listener like below.
myClockEmitter.on("minutesChange", (hour, minutes, seconds) => {
    console.log(`Minute changed: ${hour}:${minutes}:${seconds}`);
});

You can emit the event like below.
myClockEmitter.emit("minutesChange", 12, 46, 23);

Find the below working application.

HelloWorld.js
var EventEmitter = require('events').EventEmitter;

class ClockEmitter extends EventEmitter {};

var myClockEmitter = new ClockEmitter();

myClockEmitter.on("minutesChange", (hour, minutes, seconds) => {
    console.log(`Minute changed: ${hour}:${minutes}:${seconds}`);
});

myClockEmitter.on("hoursChange", (hour, minutes, seconds) => {
    console.log(`Hour changed: ${hour}:${minutes}:${seconds}`);
});

myClockEmitter.emit("minutesChange", 12, 46, 23);
myClockEmitter.emit("hoursChange", 1, 46, 23);


Output

Minute changed: 12:46:23
Hour changed: 1:46:23




Previous                                                 Next                                                 Home

No comments:

Post a Comment