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

Is there a way to tell from within the event handler callback which function and / or object selected (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();
}

It is also another use if the source of the emitted event is from the node.js. built-in module. For example, the "error" events. If I use a common callback to handle errors, can this callback find out who selected the event that caused it?

+4
source share
2 answers

Here is the solution for your specific 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

Error (). - .

+3

, this EventEmitter, . this , , . , :

object.on('event', function() {
  var value = object.value;
});
+1

Source: https://habr.com/ru/post/1535184/


All Articles