2016-08-22 77 views
0

我有指令控制器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和角度1的常用方法?

+0

你嘗試過使用:'var self = this;'concept? –

+1

@MaximShoustin:老實說,我不喜歡這種方法 – user348173

+0

我想你應該只傳遞'onLoginSuccess'而不是'this.onLoginSuccess.bind(this)' – gianlucatursi

回答

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; 
} 
+0

感謝您的詳細解答。 – user348173