EventEmitter Class in Node.JS:
In Node.js we can create event and trigger them. With Node.JS we just start our server, declare our function and then bind them with event and fire.
First we load the events module which is part of the Node.js core as :
var events = require('events');
Now we create a object of EventEmitter
var eventEmitter = new events.EventEmitter();
After hen we create a function myFunc inside a variable.
var myFunc = function myFunc()
{
console.log('Function called');
}
Now we add our function in function list which will done by eventEmitter.on() . The eventEmitter takes two argument, First one is event and second one is function which will be added.
eventEmitter.on('myevent', myFunc);
Now our function is register, but this will not execute until we called emit() method. emit() execute all the functions that are registered with the ON method.
eventEmitter.emit('myevent');
Now we run the js file and below is our output :
Function called
0 Comment(s)