EventEmitter listeners and emitters with various parameters

Can we have several emitter listeners, each of which works with a different number of arguments?

eg. let the 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 value is true, then which parameter goes to the one who is listening?

+7
javascript mocha protractor eventemitter
source share
2 answers

Listeners listen only to normal JS functions. Thus, you can pass as many arguments as you want, but the function can only access the arguments that you specified in the definition of the function ie

 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!'); 

In fact, you can see that all the arguments provided are always passed to each function. But if you do not specify the argument names in the function declaration, you cannot directly access these arguments. But you can use the magic argument in each function to access all the arguments provided. Of course, the argument is provided to the function in the order in which they were passed to the EE.

+14
source share

EventEmitter seems to call all listeners using the apply method. Therefore, each listener can expect to receive arguments in the same order that is passed to the emit function. The following code demonstrates that a listener without parameters will still receive all the 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'); 
+4
source share

All Articles