简体   繁体   English

如何在 node.js 事件监听器中获取事件名称?

[英]How to get event name in node.js event listener?

I am dynamically creating event listener for some events.我正在为某些事件动态创建事件侦听器。 In that event listener i want to do another emit call based on the event name, so i want to get the event listener name在那个事件侦听器中,我想根据事件名称进行另一个发出调用,所以我想获取事件侦听器名称

I am using node.js eventemitter.我正在使用 node.js 事件发射器。

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

       .....
       .....

     for(i in events) {
        transport.on(events[i],function(userId) {
            eventName = events[i];
            var acct = accountsList[userId];
            if(acct) {
                acct.emit(events[i],userId);
            }
        });
    }

The above method is working but the problem line is上述方法有效,但问题线是

       acct.emit(events[i],userId);

that events[i] is having last value of the loop.那个 events[i] 具有循环的最后一个值。 so if received any event it always emitting the final loop of the events[i] value...因此,如果收到任何事件,它总是会发出 events[i] 值的最终循环...

So you are preserving value of event_name in a closure.因此,您在闭包中保留了event_name的值。 It is legal, but doesn't look very neat.这是合法的,但看起来不是很整洁。

Instead, you could use EventEmitter2 module like this相反,您可以像这样使用EventEmitter2模块

var EventEmitter = require('eventemitter2').EventEmitter2;

var emitter = new EventEmitter();

emitter.on('ev1', function (line) {  
  console.log(this.event); // here's your fired event
});

emitter.emit('ev1', 'has fired');

Check out the documentation, you could do much more than the original EventEmitter查看文档,您可以做的比原来的EventEmitter更多

i overcome this by function ...but i want to know this right way or not...我通过功能克服了这个......但我想知道这个正确的方式......

   for(i in events) {
     function test(event_name){
        transport.purpleEvents.on(event_name,function(userId) {
            var acct = accountsList[userId];
            if(acct) {
                acct.emit(event_name,userId);
            }
        });
      }
      test(events[i]);
    }

The for loop you are using is async and results in all calls using the last value in events.您使用的 for 循环是异步的,并导致所有调用都使用事件中的最后一个值。 If you replace that with forEach it will run sync.如果你用 forEach 替换它,它将运行同步。 Try something like this untested code:尝试类似以下未经测试的代码:

 events.forEach(function(i) {
    transport.on(events[i],function(userId) {
        eventName = events[i];
        var acct = accountsList[userId];
        if(acct) {
            acct.emit(events[i],userId);
        }
    });
});

you can use a closure like this which can be practical soln..你可以使用像这样的封闭,这可以是实用的解决方案..

for(i in events) {
        transport.on(events[i],closureplusopn(events[i]))
     }

     function closureplusopn(eventName){
          return function(userID){

            var acct = accountsList[userId];
            if(acct) {
                acct.emit(eventName,userID);
            }
         }
     }

You can pass the event name through the context param.您可以通过上下文参数传递事件名称。 On EventEmitter3 the .on function params are (eventName, functionName, context).在 EventEmitter3 上,.on 函数参数是 (eventName, functionName, context)。 What helped me figure out how to get the eventName in the callback function was to pass this string as context and access it with the this keyword.帮助我弄清楚如何在回调函数中获取 eventName 的是将此字符串作为上下文传递并使用 this 关键字访问它。 Hope this helps whoever comes to this question and has something like this as an issue.希望这对遇到这个问题并且有类似问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM