0

I have an object оf inherited from EventEmiter "class".

It has many events (emitter.on) and I don't know their names.
How can I get their names? And how can I handle ALL events?

Dmitry
  • 7,457
  • 12
  • 57
  • 83

2 Answers2

2

You can not programatically get all possible events that will be emitted on a specific event emitter. You may be able to do so by reading the source code, however.

The only way to handle all events at runtime, that I know of, is to overwrite the emit function for that one EventEmitter. Your code will then be called whenever an event gets emitted, and you can forward it to the original function.

var EventEmitter = require("events").EventEmitter

var emitter = new EventEmitter();

emitter.on('test', function(t) {
    console.log('Handled test', t);
});

var old_emit = emitter.emit;
emitter.emit = function() {
    console.log("Intercepted", arguments);
    old_emit.apply(emitter, arguments);
}

emitter.emit('test', 'hi');
emitter.emit('something', 'else');

demo: http://ideone.com/RfqFvx

WouterH
  • 1,345
  • 10
  • 16
1

EventEmitter has own events as well, one of them: newListener, which will pass event name and callback function when new listener is added.

Additionally you can use emitter.listeners in order to get list of callback functions for specific event name.

You might want to use one event name, and send object with identification of object name, that way you can have one event, but response to it differently.

moka
  • 22,846
  • 4
  • 51
  • 67