0

Can I have access to the name of an event from within the callback which is executed when the event is triggered?

Consider the following example, where I have the same callback (handleEvent)for two differenct events. Now I want to add a conditional statement in the callback based on the event that triggered its execution. Is this possible?

obj.on('start', handleEvent);
obj.on('stop', handleEvent);

function handleEvent() {
       // how can I check here if the event that triggers the execution of handleEvent is 'start' or 'stop'

}

What I do at the moment is to pass the event two times with 'emit' - which seems to be working fine, but i don't like to write it twice:

obj.emit('start', 'start', handleEvent);
balafi
  • 2,143
  • 3
  • 17
  • 20

2 Answers2

0

Try EventEmitter2:

var EventEmitter = require('eventemitter2').EventEmitter2
var emitter = new EventEmitter

emitter.on('test', onEvent)
emitter.emit('test')

function onEvent() {
  console.log(this.event)
}
vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
0

You can do:

obj.on('start', handleEvent.bind({ event: 'start' }));
obj.on('stop', handleEvent.bind({ event: 'stop' }));

function handleEvent() {
    if(this.event == 'start') { ///
}
levi
  • 23,693
  • 18
  • 59
  • 73