Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In node.js, how to tell the source of an emitted event?

Is there a way to tell from within an event handler callback which function and/or object emitted (called) the event?

Here is an example program:

var EventEmitter, ee, rand, obj;
EventEmitter = require("events").EventEmitter;

ee = new EventEmitter();
ee.on('do it', cFunc);

obj = {
    maybeMe:    true,
    emitting:   function() {
                    ee.emit('do it');
                }
}
function aFunc() {
    ee.emit('do it');
}
function bFunc() {
    ee.emit('do it');
}
function cFunc() {
    console.log('Who called me to do it?  aFunc or bFunc or obj (obj.emitting)?');
}

rand = Math.random(); 

if (rand < .3) {
    aFunc();
} else if (rand < .6) {
    bFunc();
} else {
    obj.emitting();
}

Also, another use, if the source of the emitted event is from a node.js built in module. For example, 'error' events. If I use a common callback for error handling, can this callback know who emitted the event which called it?

like image 745
ciso Avatar asked Oct 01 '22 03:10

ciso


1 Answers

Here a solution for your particular example:

function cFunc() {
    var caller = new Error().stack.split("\n")[3].trim().substring(3).split(" (")[0];
    console.log('Who called me to do it?  aFunc or bFunc or obj (obj.emitting)?');
    console.log(caller);
}

explanation

We use Error to get current stack (more info). The stack is represented as a string - the fourth line represents the calling function.

like image 166
artur grzesiak Avatar answered Oct 13 '22 11:10

artur grzesiak