Wednesday 3 October 2018

EventEmitter: newListener event

This event is emitted before a listener is added to its internal array of listeners.

Below table summarizes the arguments of callback function to newListener event.
Argument
Type
Description
eventName
String
The name of the event being listened for
listener
Function
Event handler function

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

var em = new EventEmitter();


em.on('newListener', (event, listener) =>{
 console.log(`New listener is added for the event '${event}'`);
});


em.on('demoEvent', () => {
  console.log('Listener1 is added for demoEvent');
});

em.on('demoEvent', () => {
  console.log('Listener2 is added for demoEvent');
});

em.emit('demoEvent');


Output
New listener is added for the event 'demoEvent'
New listener is added for the event 'demoEvent'
Listener1 is added for demoEvent
Listener2 is added for demoEvent

There is one side effect with ‘newListener’ event, since this event is called before adding the actual listener, any listener added in this 'newListener' callback will be inserted before the listener that is in the process of being added.


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

var em = new EventEmitter();

em.once('newListener', (event, listener) => {
    em.on('demoEvent', () => {
        console.log("B");
    })
});


em.on('demoEvent', () => {
    console.log('A');
});

em.emit('demoEvent');

Output
B
A



Previous                                                 Next                                                 Home

No comments:

Post a Comment