I have a function that logs in a user successfully.
_login: function() {
var email = this.$.emailvalue.value;
var password = this.$.passwordvalue.value;
return this.$.authenticate.signInWithEmailAndPassword(email, password).then(function() {
// Sign-in successful.
//this._animateView(); **returns undefined**
}, function(error) {
// An error happened.
// // Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
// this._animateErrorView(); **returns undefined**
});
},
What I want is to call a function this._animateView();
when a user logs in successfully and this._animateErrorView()
when there is an error.
If I try to do that It returns undefined.. How do I solve this issue
The meaning of
this
is different in the callback function.You can fix this in many ways, but here are two.
capture the value of this in another variable
You cannot prevent
this
from getting a new value, since that's simply how JavaScript closures work. But what you can do is define a different value with the value that you need. A idiomatic name for the variable isself
, although I personally prefer something more descriptive:use fat arrow functions
ES6 defines a new way to declare functions with so-called fat arrows (
=>
). Aside from being slightly less code, these ensure the value ofthis
in the lambda/callback remains unchanged. So