最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass parameter to EventEmitter.on method in node.js - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Aug 14, 2017 at 10:06 Adarsh TrivediAdarsh Trivedi 5822 gold badges9 silver badges24 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 25

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

发布评论

评论列表(0)

  1. 暂无评论