Sunday, 7 October 2018

node.js: emitter.off(eventName, listener)

emitter.off(eventName, listener)
It is an alias for emitter.removeListener(). It removes the specified listener from the listener array for the event named eventName.

HelloWorld.js
var util = require('util');

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

var emitter = new EventEmitter();

var listener1 = () =>{
 console.log("listener1: Hello World");
};

var listener2 = (name) => {
 console.log(`listener2: Hello Mr ${name}`);
};

emitter.on('Hello', listener1);
emitter.on('Hello', listener2);

console.log("Emitting 'Hello' event\n");
emitter.emit('Hello', "Krishna")

console.log("\nRemoving listener1\n")
emitter.off('Hello', listener1);

console.log("Emitting 'Hello' event\n");
emitter.emit('Hello', "Krishna")


Output
Emitting 'Hello' event

listener1: Hello World
listener2: Hello Mr Krishna

Removing listener1

Emitting 'Hello' event

listener2: Hello Mr Krishna




Previous                                                 Next                                                 Home

No comments:

Post a Comment