Monday 8 October 2018

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

emitter.removeListener(eventName, listener)
Removes the specified listener from the listener array for the event named eventName.

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

var emitter = new EventEmitter();

var helloListener = () => {
 console.log('Hello!!!!!');
};

var goodMorningListener = () => {
 console.log('Good Morning.......');
};

console.log('Registering "sayHello" and "goodMorning" events');
emitter.on('sayHello', helloListener);
emitter.on('goodMorning', goodMorningListener);

console.log('\nEmitting "sayHello" and "goodMorning" events');
emitter.emit('sayHello');
emitter.emit('goodMorning');

console.log('\nRemoving "sayHello" listener');
emitter.removeListener('sayHello', helloListener);

console.log('\nEmitting "sayHello" and "goodMorning" events');
emitter.emit('sayHello');
emitter.emit('goodMorning');

Output
Registering "sayHello" and "goodMorning" events

Emitting "sayHello" and "goodMorning" events
Hello!!!!!
Good Morning.......

Removing "sayHello" listener

Emitting "sayHello" and "goodMorning" events
Good Morning.......


 If a single listener is registered multiple times for the same event, then 'removeListener()' remove only one instance of the listener function.

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

var emitter = new EventEmitter();

var helloListener = () => {
 console.log('Hello!!!!!');
};


console.log('Registering "helloListener" 3 times');
emitter.on('sayHello', helloListener);
emitter.on('sayHello', helloListener);
emitter.on('sayHello', helloListener);

console.log('\nEmitting "sayHello" event');
emitter.emit('sayHello');

console.log('\nRemoving "helloListener" listener');
emitter.removeListener('sayHello', helloListener);

console.log('\nEmitting "sayHello" and "goodMorning" events');
emitter.emit('sayHello');


Output
Registering "helloListener" 3 times

Emitting "sayHello" event
Hello!!!!!
Hello!!!!!
Hello!!!!!

Removing "helloListener" listener

Emitting "sayHello" and "goodMorning" events
Hello!!!!!
Hello!!!!!






Previous                                                 Next                                                 Home

No comments:

Post a Comment