`onStartedProcess` callback never get called [duplicate] - javascript

This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 4 years ago.
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

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

Related

Method not recognized even though it is from the same class in Javascript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
Recently, I've come across this problem where I had two methods in a class. One was referring to another but the other wasn't being recognized even though I could execute them individually.
class ButtonProcessor {
buttonClick() {
this.otherMethod();
}
otherMethod() {
console.log("This does not work!");
}
}
var buttonProcessor = ButtonProcessor;
document.getElementById("button").onclick = buttonProcessor.buttonClick;
The first method was called from a button click which was associated with a callback to that method.
One solution I found for this is to make the method that is called by the button a seperate function from the class and make it reference a class object that was already being used else-where. This is because apparently, when a method is referenced in a callback, using this to refer to another method doesn't work, because the callback only considers that one method.
class ButtonProcessor {
otherMethod() {
console.log("This does work!");
}
}
var buttonProcessor = ButtonProcessor;
function buttonClick() {
buttonProcessor.otherMethod();
}
document.getElementById("button").onclick = buttonProcessor.buttonClick;
Could there be another way to fix this?

How to call a class method from inside same class method? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I've created a class and I'm trying to call a method from inside that class from another method inside that same class. I've seen online that some people say use 'this' keyword, but as you can see from the example, that doesn't work. Can someone please explain in simple terms how to call a class method from inside another method in that same class? Thanks!
class Form {
constructor() {
}
fn1 () {
console.log('fn1 calling fn2 now:')
this.fn2();
}
fn2 () {
console.log('fn1 called me')
}
}
let myForm = new Form();
myForm.fn1();
Example can be found here
The error I keep getting is this: Uncaught TypeError: this.fn2 is not a function
There's nothing wrong with the code you show embedded into your question - that should work just fine. The issue arises when you pass a method to .addEventListener() as a callback (which shows in the code you have a link to).
Change this:
document.getElementById('call-func').addEventListener('click', this.fn1);
to this:
document.getElementById('call-func').addEventListener('click', this.fn1.bind(this));
The problem is that passing this.fn1 loses the value of this so when the listener calls the callback later, the object that it belongs to is lost and then this inside of fn1() is wrong. In addition, .addEventListener() explicitly sets the this value to the DOM element that triggered the event (which is not your object).
The same thing would happen if you did this:
let f = this.fn1;
f();
Using .bind(this) rebinds the value of this when the listener calls it.
FYI, you could also do it this way with a fat-arrow function:
document.getElementById('call-func').addEventListener('click', () => this.fn1());
Or, an older way of doing it:
var self = this;
document.getElementById('call-func').addEventListener('click', function() {
self.fn1();
});
My preference is to use .bind(this).
More explanation on event listeners and this here: "This" within es6 class method
More explanation on the general concept of how this gets set when a function is called here: When you pass 'this' as an argument

How does this javascript class and method work? [duplicate]

This question already has answers here:
Where do the parameters in a javascript callback function come from?
(3 answers)
Closed 4 years ago.
As seen here from Twilio's documentation, how does the following code work? We have a connection class and an on method. If I haven't previously defined what hasEarlyMedia, showRingingIndicator, or playOutgoingRinging mean, then how does the on method know what they mean and what to do with them? Thanks.
connection.on('ringing', function(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) { playOutgoingRinging(); }
});
Maybe is easier to understand if we rewrite the code like this:
// when the Connection has entered the ringing state,
// call handleRingingEvent (callback function) and pass an argument,
// a boolean denoting whether there is early media available from the callee
connection.on('ringing', handleRingingEvent);
function handleRingingEvent(hasEarlyMedia) {
showRingingIndicator();
if (hasEarlyMedia) {
playOutgoingRinging();
}
}
// if not defined somewhere else
function showRingingIndicator() {
// do something
}
// if not defined somewhere else
function playOutgoingRinging() {
// do something
}
I hope this helps.
hasEarlyMedia is an argument. Please check
showRingingIndicator(); and playOutgoingRinging(); method must be defined somewhere. Must be function declared in your one of the library which you have included in your file.

Uncaught TypeError: this.method is not a function - Node js class export [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I am new to node.js and I am trying to require a class. I have used https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes as reference. However, when I do this for example:
// talker.js
class Talker {
talk(msg) {
console.log(this.say(msg))
var t = setTimeout(this.talk, 5000, 'hello again');
}
say(msg) {
return msg
}
}
export default Talker
// app.js
import Talker from './taker.js'
const talker = new Talker()
talker.talk('hello')
I get:
talker.js:4 Uncaught TypeError: this.say is not a function
It should be said that app.js is the electron.js renderer process and it bundled using rollup.js
Any ideas why this would be?
Update: Sorry, I forgot to add in a line when putting in the psuedo code. It actually happens when I call setTimeout with callback. I have updated the code.
You are losing the bind of this to your method.
Change from this:
setTimeout(this.talk, 5000, 'hello again');
to this:
setTimeout(this.talk.bind(this), 5000, 'hello again');
When you pass this.talk as a function argument, it takes this and looks up the method talk and passes a reference to that function. But, it only passes a reference to that function. There is no longer any association with the object you had in this. .bind() allows you to pass a reference to a tiny stub function that will keep track of this and call your method as this.say(), not just as say().
You can see the same thing if you just did this:
const talker = new Talker();'
const fn = talker.say;
fn();
This would generate the same issue because assigning the method to fn takes no associate to talker with it at all. It's just a function reference without any association with an object. In fact:
talker.say === Talker.prototype.say
What .bind() does is create a small stub function that will save the object value and will then call your method using that object.

How to know what parameters are available in jQuery callback functions, how to understand it and add parameters?

I am currently developing a map with the Openlayers 3 library and need to understand the callback functions.
I then started reading and found out I've been using callback functions with jQuery all the time.
I also read that you can use parameters that are available in these functions:
$('body').click(function(e){
e.preventdefault();
)}
The 'e' can be used in the function.
My questions are:
How to know what parameters are available?
Can you add parameters to this function?
Where are these parameters defined?
I am trying to understand this because I would have to use global parameters otherwise, and using global parameters is considered 'bad practice', right?
EDIT:
So if I want to add an extra parameter to the function above, will this work:
document.ready(function(){
var data = 6;
$('body').click(function(e, data){
e.preventdefault();
console.log(data);
})
})
The parameters to the callback functions are documented in the specific API you're using.
For example, the reference for the click-method in jQuery can be found here: https://api.jquery.com/click/
If you want to add parameters to the function you can use variables from outside the function, they will be available inside that function:
document.ready(function(){
var data = 6;
$('body').click(function(e){ // Note: don't add 'data' in the parameter here, it will overwrite your local variable with whatever jquery passes to the function.
e.preventdefault();
console.log(data); // data = 6, it's available from the outer function
})
})
Since the callback will not be executed when you attach the handler (aka when you call $("body").click() sometimes you will need to make sure the variable that is available when executing has the same value as when the handle was attached.
Say you have the following declaration:
var data = 6;
$('body').click(function(e){
e.preventDefault();
console.log(data);
});
data = 10;
In the above case, the console.log(data) statement will output 10. Why? Because by the time the user clicks, the last statement will already have executed and that will have modified data to hold the value 10.
To fix this issue, you need to capture the variable inside a closure:
var data = 6;
$('body').click((function(myVar){
return function(e){
e.preventDefault();
console.log(myVar);
}
})(data));
data = 10;
Here, the value 6 will be logged to the console. Why? Instead of passing a plain function to the click-handler, you're declaring a function and immediately executing it like this:
(function(){
})()
From this IIFE(immediately invoked function expression), you return another function that will be used as the handler for the click event. The variable you pass in to the IIFE will be captured and will keep the same value as it was when you attached the click-handler

Categories

Resources