[英]How to avoid bind(this) in Angular directive controllers
我有用於指令控制器的ES6類:
export default class LoginController {
constructor($state, store, auth, principal) {
this.$state = $state;
this.store = store;
this.auth = auth;
this.principal = principal;
this.loginFailed = false;
this.loginErrorMessage = '';
}
onLoginSuccess(profile, token) {
this.store.set('profile', profile);
this.store.set('token', token);
this.principal.updateCurrent(profile, token);
this.$state.go('main');
}
onLoginFailed(error) {
this.loading = false;
this.loginFailed = true;
this.loginErrorMessage = error.details.error_description;
}
signGoogle() {
this.signOAuth('google-oauth2');
}
signOAuth(connection) {
this.loading = true;
this.auth.signin({
popup: true,
connection: connection,
scope: 'openid name email'
}, this.onLoginSuccess.bind(this), this.onLoginFailed.bind(this));
}
}
LoginController.$inject = [
'$state', 'localStorageService', 'auth', 'principal'
];
在signOAuth
方法中,我有兩個回調: onLoginSuccess
和onLoginFailed
。 為了正確地調用它們,我必須使用bind(this)
否則在calbacks中將this
undefined
。
是否可以避免bind
? 還是使用ES6和angular 1的正常方法?
您可以將綁定移動到構造函數,如果有幫助(不是真的):
constructor($state, store, auth, principal) {
this.$state = $state;
this.store = store;
this.auth = auth;
this.principal = principal;
this.loginFailed = false;
this.loginErrorMessage = '';
this.onLoginSuccess = this.onLoginSuccess.bind(this);
this.onLoginFailed = this.onLoginFailed.bind(this);
}
...,添加一個間接級別:
this.auth.signin({
popup: true,
connection: connection,
scope: 'openid name email'
},
(profile, token) => this.onLoginSuccess(profile, token),
(error) => this.onLoginFailed(error)
)
...,或創建類實例字段(這可能需要您向Transpiler中添加其他插件,因為它們不是ES2015 AFAIK的一部分;對於Babel,我認為transform-class-properties
處理這些問題):
onLoginSuccess = (profile, token) => {
this.store.set('profile', profile);
this.store.set('token', token);
this.principal.updateCurrent(profile, token);
this.$state.go('main');
}
onLoginFailed = error => {
this.loading = false;
this.loginFailed = true;
this.loginErrorMessage = error.details.error_description;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.