Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to EventEmitter.on method in node.js

I have just started exploring node.js and below is situation with me while learning events handling in node.js.

I have an event 'loop' and a function 'myLoopHandler' attached to it using the method

eventEmitter.on('loop',myLoopHandler);

And the myLoopHandler is defined as follows:

var myLoopHandler = function(){
for(i=1;i<=30;i++)
    console.log(i);
}

And then I emit the event 'loop' :

eventEmitter.emit('loop');

How do I pass some parameter to the myLoopHandler function in eventEmitter.on method?

I am open to any other way of achieving the same.

like image 681
Adarsh Trivedi Avatar asked Aug 14 '17 10:08

Adarsh Trivedi


People also ask

How do you pass a parameter to an event?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

How do I use event emitters in NodeJS?

The following example demonstrates EventEmitter class for raising and handling a custom event. // get the reference of EventEmitter class of events module var events = require('events'); //create an object of EventEmitter class by using above reference var em = new events. EventEmitter(); //Subscribe for FirstEvent em.

How do I add a listener to EventEmitter?

on(event, listener) and eventEmitter. addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener's array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times.


1 Answers

just do

emitter.emit(eventName[, ...args])

where args is the arguments to emit

this is an example

const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this);
  // Prints:
  //   a b MyEmitter {
  //     domain: null,
  //     _events: { event: [Function] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined }
});
myEmitter.emit('event', 'a', 'b');

source NodeJS docs

like image 181
marvel308 Avatar answered Oct 31 '22 04:10

marvel308