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.
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 is self
, although I personally prefer something more descriptive:
_login: function() {
var email = this.$.emailvalue.value;
var password = this.$.passwordvalue.value;
var self = this;
return this.$.authenticate.signInWithEmailAndPassword(email, password).then(function() {
self._animateView();
}, function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
self._animateErrorView();
});
}
ES6 defines a new way to declare functions with so-called fat arrows (=>
). Aside from being slightly less code, these ensure the value of this
in the lambda/callback remains unchanged. So
_login: function() {
var email = this.$.emailvalue.value;
var password = this.$.passwordvalue.value;
return this.$.authenticate.signInWithEmailAndPassword(email, password).then(() => {
this._animateView();
}, (error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
this._animateErrorView();
});
}