Javascript, node, Q promises, prototype functions, and "this"
Problem
I don't really understand why "this" is undefined in my handleAuthSuccess function, but I imagine it has something to do with it being called by the promise.
Can anyone explain? What is the a proper working way to do something like what I'm trying to accomplish here?
Client.prototype.authenticate = function (email, password) {
authenticationService.authenticate(email, password).then(this.handleAuthSuccess, this.handleAuthError);
};
Client.prototype.handleAuthSuccess = function (email) {
console.log("Credentials verified. Proceeding with login.");
this.session.auth.isAuthenticated = true;
this.session.auth.id = email;
var response = { Type: 'login success' };
this.send(response);
};
Problem courtesy of: CodeMonkeyCharlie
Solution
You need to bind your callbacks so they have the proper this
.
.then(this.handleAuthSuccess.bind(this), this.handleAuthError.bind(this))
You can also bind the functions in your constructor, like this:
this.handleAuthSuccess = this.handleAuthSuccess.bind(this);
and then call the function as you are doing now.
Solution courtesy of: loganfsmyth
Discussion
There is currently no discussion for this recipe.
This recipe can be found in it's original form on Stack Over Flow.