Node.js events add event listener

Description

Node.js events add event listener


// Create events and Event Emitter
var events = require('events');
var eventEmitter = new events.EventEmitter();

// listener #1//from   ww  w. j  a  v  a  2s  .  c  o  m
var listner1 = function listner1() {
  console.log('listner1 executed.');
}

// listener #2
var listner2 = function listner2() {
  console.log('listner2 executed.');
}
// Bind the connection event with the listner1 function
eventEmitter.addListener('connection', listner1);

// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);

var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log("# of listeners listening to connection eventListeners is " + eventListeners);

// Fire the connection event
eventEmitter.emit('connection');

// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will now not ever listen.");

var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log("# of listeners listening to connection eventListeners is " + eventListeners);

console.log("Program Ended.");



PreviousNext

Related