2

I would like to use an event in node.js to execute some code; my question is, what is the scope of the invoked event code? Specifically, does it share the scope of the event invoker, or is it "isolated"? I know that I can pass parameters to the code invoked on the event to achieve a similar effect, but ideally I'd like to have the invoking scope available.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117

2 Answers2

4

The event is tied to the scope of the invoker. i.e. an EventEmitter exported from a module, can only be used to listen for events emitted from that same EventEmitter.

Nodejs EventEmitter - Define scope for listener function

Community
  • 1
  • 1
Brian P Johnson
  • 703
  • 6
  • 17
2

When you emit an event, you put it into a queue to be processed later by the node event system. Any variables from the scope where the event is emitted must be passed to emit as arguments. When node takes that event and triggers all bound callbacks, that happens under both a distinct "clean" scope and a distinct "clean" stack. (Side note, this is why stack traces in node can be a nuisance for debugging).

var events = require('events');

var myEmitter = new events.EventEmitter();

function closure1(word, number) {
  function closure2(animal, vegetable) {
    myEmitter.emit('hey', word, number, animal, vegetable, 43);
  }
  closure2("horse", "carrot");
}

myEmitter.on('hey', function (word, number, animal, vegetable, anotherNumber) {
  console.log('hey event fired with', word, number, animal, vegetable, anotherNumber);
});
closure1("table", 42);

When you run that, it will print "hey event fired with table 42 horse carrot 43".

see the node.js docs on emitter.emit(event, [arg1], [arg2], [...]

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274