我有指令控制器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)
,否則我得到undefined
爲this
在回調中。
是否可以避開bind
?或者,這是使用ES6和角度1的常用方法?
你嘗試過使用:'var self = this;'concept? –
@MaximShoustin:老實說,我不喜歡這種方法 – user348173
我想你應該只傳遞'onLoginSuccess'而不是'this.onLoginSuccess.bind(this)' – gianlucatursi