gpt4 book ai didi

javascript - 如何避免 Angular 指令 Controller 中的绑定(bind)(this)

转载 作者:行者123 更新时间:2023-12-03 06:16:31 28 4
gpt4 key购买 nike

我有用于指令 Controller 的 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 方法中,我有两个回调:onLoginSuccessonLoginFailed。为了正确调用它们,我必须使用 bind(this) ,否则我会在回调中得到 thisundefined

是否可以避免绑定(bind)?或者,这是使用 ES6 和 Angular 1 的正常方法?

最佳答案

您可以将绑定(bind)移动到构造函数,如果这有帮助(不是真的):

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)
)

...,或者创建类实例字段(这可能需要您向转译器添加额外的插件,因为它们不是 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;
}

关于javascript - 如何避免 Angular 指令 Controller 中的绑定(bind)(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39075971/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com