eventEmitter listeners and emitters with different parameters

16,701

Solution 1

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.

Solution 2

The EventEmitter appears to call all listeners using the apply method. Therefore, every listener can expect to receive arguments in the same order passed to the emit function. The following code demonstrates that the parameterless listener still receives all arguments to the function.

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

var ee = new EventEmitter();

ee.on('myEvent', function() {
    console.log('no arguments');
    console.log(arguments); // Outputs: { '0': 'arg 1', '1': 'arg 2' }
});

ee.on('myEvent', function(arg1, arg2) {
    console.log('with arguments');
    console.log(arg1);
    console.log(arg2);
});

ee.emit('myEvent', 'arg 1', 'arg 2');
Share:
16,701
nirvanastack
Author by

nirvanastack

Updated on July 22, 2022

Comments

  • nirvanastack
    nirvanastack almost 2 years

    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?

  • nirvanastack
    nirvanastack almost 10 years
    Got it. So all arguments are passed no matter how many arguments are there in the function declaration. If not explicitly defined they will be received in the magic argument object. Thanks people
  • nirvanastack
    nirvanastack almost 10 years
    Thanks Hayes for the quick response