I am new to Nodejs, and I have a question about the EventEmitter
's listenerCount()
method, but also the way of calling static methods in general. This is the sample code from TutorialsPoint's Nodejs tutorial on the event emitter:
var events = require('events');
var eventEmitter = new events.EventEmitter();
// listener #1
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(eventListeners + " Listner(s) listening to connection event");
// Fire the connection event
eventEmitter.emit('connection');
// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");
// Fire the connection event
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
console.log("Program Ended.");
It calls the listenerCount()
method on the events
"class" (is it a class?) by requiring the events again. I am referring to the part where it says:
var eventListeners = require('events').EventEmitter.listenerCount
(eventEmitter,'connection')
listenerCount()
is essentially a static method, I suppose, since you cannot call it on the events
object directly.
(I also don't quite understand why the implementation is such, and why wouldn't it be implemented so that I could invoke it on my eventEmitter
object, such as: eventEmitter.listenerCount('connection')
)
But either way, what I have then tried, is to call this static method on my events
object, without the additional require
call (on both instances in this code), so that it looked like this:
events.EventEmitter.listenerCount(eventEmitter, "connection");
And the output of the program was the same.
So my question about this is, is there an actual reason the author called it by making a new require
for each of those calls, and is there (or could there be) any difference in the behavior of the way the calls were made in the original code, and my alteration?
FWIW you can actually use
emitter.listenerCount()
directly since at least node v4.0.0.As for the extra
require()
, it's not needed and you can do what you have suggested (events.EventEmitter.listenerCount()
).