1

I bind a function with this code

this.process[id].on('started', this.onStartedProcess.bind(this)); // I    want to pass an extra variable here. 

Then, in the process, when I call this code

that.emit('started', {startTime:time, instance: that});

The following function is called

onStartedProcess(info) {
console.log(info.startTime);
}

Is it possible to pass an extra variable to the onStartedProcess function when biding it? Something like

this.process[id].on('started', this.onStartedProcess.bind(this,otherParameter));

and use the parameter when the onStartedProcess is called because of the emit, for example

onStartedProcess(info, otherParameter) {
console.log(info.startTime);
console.log(otherParameter);
}

I red this post about the bind method but still can't find a way to achieve what I want to do.

Edit: This is not working for me. This is what I tried

this.process[id].on('started', this.onStartedProcess.bind(this, 5));

that.emit('started', {startTime:time, instance: that});

    onStartedProcess(info, otherParameter) {
    console.log(otherParameter); // I was expecting the get the 5 here
    }

onStartedProcess never get called

Carloluis
  • 4,205
  • 1
  • 20
  • 25
user567
  • 3,712
  • 9
  • 47
  • 80
  • yes this is how `bind` work, first parameter is the `this` value inside the 'binded' function, other parameters are the function parameters in the order of their declaration. You may give only one, two or all parameters. – Pierre Feb 28 '18 at 12:19
  • Yes that should work. Read this [link](https://stackoverflow.com/a/20925268/3008050) for detailed understanding. – karan3112 Feb 28 '18 at 12:21
  • This is not working for me – user567 Feb 28 '18 at 12:44

1 Answers1

1

Yes. You are describing how bind function works. First pass the context (this), then all additional parameters you need. Read the docs here


The problem is with the arguments order in the function you are binding.

onStartedProcess(info, otherParameter) {
    // with your current `.onStartedProcess.bind(this, 5)
    // you are binding `info` argument to `5`
    console.log(otherParameter); // I was expecting the get the 5 here
}

If you want to currently set otherParameter to 5 you need to properly bind the second argument: .bind(thisArg, firstArg, SecondArg)


Regarding to the callback not being called. This is one solution for your scenario:

// parent.js

const { fork } = require('child_process');
const subprocess = fork('child.js');

subprocess.send('start');
subprocess.send({ hello: 'world' });

// child.js

process.on('message', onStartedProcess.bind(null, 'first arg', 5));

function onStartedProcess(info, otherParameter, message) {
    console.info('callback args:', info, otherParameter, message);
}

Running node parent.js you should get this output:

callback args: first arg 5 start

callback args: first arg 5 { hello: 'world' }


Read more about node process messaging here

Community
  • 1
  • 1
Carloluis
  • 4,205
  • 1
  • 20
  • 25