【问题标题】:How to avoid bind(this) in Angular directive controllers如何避免 Angular 指令控制器中的 bind(this)
【发布时间】: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 方法中,我有两个回调:onLoginSuccessonLoginFailed。要正确调用它们,我必须使用 bind(this) 否则我会在回调中得到 undefinedthis

是否可以避免bind?或者,这是使用 ES6 和 angular 1 的正常方法?

【问题讨论】:

  • 您是否尝试使用:var self = this; 概念?
  • @MaximShoustin:老实说,我不喜欢这种做法
  • 我认为你应该只通过 onLoginSuccess 而不是 this.onLoginSuccess.bind(this)

标签: javascript angularjs ecmascript-6


【解决方案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)
)

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

【讨论】:

  • 感谢您的详细解答。
猜你喜欢
  • 1970-01-01
  • 2015-12-30
  • 2017-06-05
  • 1970-01-01
  • 2016-06-14
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多