2014-03-01 27 views
0

我正嘗試使用Facebook登錄Ember應用程序。登錄操作正在工作,但我無法找到如何檢查用戶是否已在應用程序初始化時登錄。Emberjs:檢查用戶是否在初始化時使用Facebook登錄

我打電話給auth.authResponseChange事件,但它阻止了應用程序,它永遠不會啓動。

App.ApplicationController = Ember.Controller.extend({ 
    fbUser: false, 

    init: function() { 
     this.checkFBUser() 
    }, 

    checkFBUser: function() { 
     FB.Event.subscribe('auth.authResponseChange', function(response) { 
     // this is never triggered and the app does not init 
     console.log(response) 
     if (response.status === 'connected') { 
      console.log('Logged in') 
     } 
     else { 
      FB.login() 
     } 
     }) 
    }, 

    // this works 
    actions: { 
     loginFacebook: function() { 
     var self = this 

     FB.login(function(response) { 
      if (response.authResponse) { 
      FB.api('/me', function(response) { 
       self.set('fbUser', response) 
      }) 
      } 
     }) 
     } 
    } 
    }) 

我該怎麼做?

回答

0

我發現的問題和解決的根源。我不確定這是最好的解決方案,所以我願意接受其他建議,但是如果這可以幫助其他人,則可以這樣做:

問題是Facebook庫尚未加載,所以FB變量未定義。出於某種原因,如果您嘗試在Ember中使用未定義的變量來執行某些操作,則即使沒有警告,該應用也無法正常工作。所以,解決的辦法就是等待:

App.deferReadiness() 

function checkFB() { 
    if (typeof FB !== 'undefined') { 
    APp.advanceReadiness() 
    } 
    else { 
    setTimeout(checkFB, 10); 
    } 
} 

setTimeout(checkFB, 10); 

10毫秒很短,所以在應用仍在初始化非常快,而且在我的測試應用程序啓動後約20毫秒。這仍然感覺有點冒失,但是取代了現在可以做的更好的解決方案。

0

我最近沒有和FB一起工作過,但我敢肯定,AuthResponeChange事件是爲了通知AuthResponse狀態的變化;在這種情況下,您可能需要查看FB.getLoginStatus。

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus

checkFBUser: function() 
{ 
    FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 
     // the user is logged in and has authenticated your 
     // app, and response.authResponse supplies 
     // the user's ID, a valid access token, a signed 
     // request, and the time the access token 
     // and signed request each expire 
     var uid = response.authResponse.userID; 
     var accessToken = response.authResponse.accessToken; 
    } else if (response.status === 'not_authorized') { 
     // the user is logged in to Facebook, 
     // but has not authenticated your app 
    } else { 
     // the user isn't logged in to Facebook. 
    } 
}); 
+0

但如果我把這個路線將只檢查了一定的網址嗎?登錄狀態必須在任何地方進行檢查。 (我是一個愚蠢的noob順便說一句,所以我不知道我在做什麼) – romainberger

+0

您可以通過使用send方法發送信號,但應用程序控制器是一個有效的選項,並且可能比爲你的目的路線。我會更新答案。 –

+0

我試過'getLoginStatus'但問題是一樣的,回調沒有被調用,應用程序沒有初始化 – romainberger

0

正如Aaron所說,您需要使用fb.getLoginStatus來檢查用戶是否已經登錄。爲了確保在您進行任何調用之前加載Facebook,您可以使用初始化程序並推遲應用程序,直到SDK加載。

http://nerdyworm.com/blog/2013/04/03/ember-initializers/

Ember.Application.initializer({ 
    name: 'init_fb', 

    initialize: function (container) { 

     window.App.deferReadiness(); 

     Ember.$.getScript('//connect.facebook.net/en_UK/all.js', function() { 

      FB.init({ 
       appId : 'xxxxxxxxxxxxx', 
       xfbml : true, 
       version : 'v2.0', 
      }); 

      window.App.advanceReadiness(); 

     }); 
    } 
});