2013-03-14 51 views
0

我有以下控制器使用ember.jsember-auth寶石。該控制器的工作原理,但每一次我得到一個標誌設置loginError財產在回調內設置控制器屬性

BaseApp.SignInController = Auth.SignInController.extend({ 
    email: null, 
    password: null, 
    loginError: false, 
    signIn: function() { 
    this.registerRedirect(); 
    Auth.signIn({ 
     email: this.get('email'), 
     password: this.get('password') 
    }); 
    this.set('loginError', true); // Sets correctly but each time 
    Auth.on('signInError', function() { 
     console.log("This is a signin error"); 
    }); 
    } 
}); 

很顯然,我希望做的是設置loginErrortrueAuth.on這樣調用的函數裏面是什麼:

BaseApp.SignInController = Auth.SignInController.extend({ 
    email: null, 
    password: null, 
    loginError: false, 
    signIn: function() { 
    this.registerRedirect(); 
    Auth.signIn({ 
     email: this.get('email'), 
     password: this.get('password') 
    }); 
    Auth.on('signInError', function() { 
     this.set('loginError', true); // Doesn't set the controller's property 
     console.log("This is a signin error"); 
    }); 
    } 
}); 

但是,這顯然不起作用,因爲回調中的範圍是不同的。也許我錯過了一些非常基本的東西。我怎樣才能使它工作?

回答

3

在傳遞給on方法的匿名函數中,上下文(即this)與控制器中的不同。您可以通過將上下文保存到閉包中的其他變量來解決此問題。

var self = this; 
Auth.on('signInError', function() { 
    self.set('loginError', true); // Should now set the controller's property 
    console.log("This is a signin error"); 
}); 
+1

也可以使用[.bind(此)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind),(用於IE它需要IE9) – harianus 2014-05-12 12:53:21

相關問題