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.
Share
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
emitas 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).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], […]