[英]Polymer firebase.. Authentication with password and email
我有一個可以成功登錄用戶的功能。
_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**
});
},
我想要的是調用一個函數this._animateView();
當用戶成功登錄時以及this._animateErrorView()
出現錯誤時。
如果我嘗試這樣做,它將返回undefined。
的意思this
是在回調函數不同。
您可以通過多種方式解決此問題,但這有兩種。
您不能阻止this
獲得新的價值,因為這正是JavaScript閉包的工作方式。 但是您可以做的是用所需的值定義一個不同的值。 變量的慣用名稱是self
,盡管我個人更喜歡更具描述性的名稱:
_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定義了一種使用所謂的胖箭頭 ( =>
)聲明函數的新方法。 除了減少一些代碼外,這些還確保在lambda / callback中的this
值保持不變。 所以
_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();
});
}
除了@Frank van Puffelen的答案外,各地的聚合物開發團隊還使用了另一種方法:
_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**
}.bind(this), function(error) {
// An error happened.
// // Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
// this._animateErrorView(); **returns undefined**
}.bind(this));
},
因此,基本上,您將.bind(this)
添加到最后的每個回調中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.