eventEmitter listeners and emitters with different parameters

nirvanastack picture nirvanastack · Jun 25, 2014 · Viewed 15.7k times · Source

Can we have multiple listeners of an emitter, each working on different number of arguments?

e.g. let event emitter be like this:

evetE.emit('pre', global, file, self);
corresponding event listeners:
//Listener 1

m.eventE.on('pre', function() {
//TODO
})

//Listener 2
eventE.on('pre', function(context, file, m){
  console.log(context.ans);
});

//Listener 3
eventE.on('pre', function(context){
  console.log(context.ans);
});

//Listener 4
this.eventE.on('pre',function (context) {})

If the above is true, then which parameter goes to which listener?

Answer

mynameisdaniil picture mynameisdaniil · Jun 25, 2014

Event listeners just regular JS functions. So you can pass as many arguments as you want, but function only can access those arguments you have declared in function definition i.e.

var EE = require('events').EventEmitter;
var ee = new EE();

ee.on('test', function (first, second, third) {
  console.log(first, second, third); //Will output full phrase
});

ee.on('test', function (first) {
  console.log(first); //Will output just first word
});

ee.on('test', function () {
  console.log.apply(console, arguments); //Will output full phrase again
});

ee.emit('test', 'Hello', 'my', 'world!');

Actually you can see that all provided arguments always passed to every function. But if you don't define argument names in function declaration you won't be able to directly access this arguments. But you can use magic "arguments" object inside every function to access all provided arguments. Ofcourse, argument provided to the function in the order they passed to EE.