Event Emitter

  • Nodejs has inbuilt EventEmitter defined in events native module
  • The following example illustrates the use:
var Emitter = require('events');
var emtr = new Emitter();
 
emtr.on('greet', function(name) {
	console.log("Hello" + " " + name);
});
 
emtr.on('greet', function(name) {
	console.log('Hola' + ' ' + name);
});
 
emtr.emit('greet', "John");
// [Output]
// Hello John
// Hola John
  • The on(type, listener) function basically define on which type which is string, does the listener will get executed
  • The emit(type, data) function actually emits the event with type and data, all the listeners with the given type will be invoked with data as input
  • Internally it is implemented by keeping track of list of listeners which will be added when on is called and executing each listener in the list when emit is called