【发布时间】:2016-08-22 09:33:45
【问题描述】:
我有指令控制器的 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 和 angular 1 的正常方法?
【问题讨论】:
-
您是否尝试使用:
var self = this;概念? -
@MaximShoustin:老实说,我不喜欢这种做法
-
我认为你应该只通过
onLoginSuccess而不是this.onLoginSuccess.bind(this)
标签: javascript angularjs ecmascript-6