Search code examples
node.jsevent-handling

Node.js: How to use variable from outer scope of event in EventEmitter?


I use newman library method run which creates EventEmitter. I do in loop and create multiple instances of EventEmitter. When event is fired, I would like to access variable from outer scope and have value which was set at time when method run was invoked (and EventEmitter created).
Pseudo code

for(i = 0; i < 1; i++) {  // Test purpose, only one iteration
   newman.run({
      ...
   })
   .on('request', (error, data) => {
      console.log(`i=${i}`);  // I expect 0, 1 is printed
   });

This implementation will display value of i from outer scope at the time when event is fired. I want to use value of i at the time when object was created. I tried to use bind() and got error that object does not have bind method. I tried to created dynamic property and got undefined.
How to get value of variable from outer scope at time when object was instantiated?


Solution

  • Found solution. Documentation of bind method:

    Function.prototype.bind() The bind() method of Function instances creates a new function that, when called, calls this function with its this keyword set to the provided value, and a given sequence of arguments preceding any provided when the new function is called.

    I should call bind() on function. My initial try was to call bind on 'arrow function' decalration. I got syntax error (Ecma script language specification. 14.2.16 Runtime Semantics: Evaluation). When I declared function and did bind(), it worked.

    function onRequest(error, data) {
        console.log(`this.id=${this.id}`);
    }
    for(i = 0; i < 1; i++) {  // Test purpose, only one iteration
       var eventemitter = newman.run({
          ...
       });
       eventemitter.on('request', onRequest.bind({id:i}));