2012-10-09 62 views
0

我有一個簡單的facebook validation我想實現我的jQuery按鈕。
當用戶點擊按鈕時,應檢查是否登錄,如果爲TRUE,則更改文本。
我發現this article談到返回true/false狀態,但是當我試圖在我的代碼中實現它,它沒有工作。

任何暗示即將出錯的建議,謝謝。facebook登錄驗證jQuery返回true/false

function fb_loginCheck(){ 
    FB.getLoginStatus(function(response, e) { 
     if (response.status === 'connected') { 
      var uid = response.authResponse.userID; 
      var accessToken = response.authResponse.accessToken; 
      e.returnValue = true; 
     } else if (response.status === 'not_authorized') { 
      // the user is logged in to Facebook, but has not authenticated your app 
      fb_oAuth(); 
      e.returnValue = false; 
     } else { 
      // the user isn't logged in to Facebook. 
      fb_oAuth(); 
      e.returnValue = false; 
     } 
    }, true); 
} 


$('.myBttn').click(function(){ 

    var io = return fb_loginCheck(); 
    if (io){ 
     $this = $(this).text(); 
     if($this == 'yes') 
      $(this).text('no'); 
     else 
      $(this).text('yes'); 
    } 

    return false; 
}); 

得到它的工作:
類似potench答案,但除去e.returnValue做到了

function fb_loginCheck(callBack){ 
    FB.getLoginStatus(function(response) { 
     if (response.status === 'connected') { 
      var uid = response.authResponse.userID; 
      var accessToken = response.authResponse.accessToken; 
      callBack(true); 
     } else if (response.status === 'not_authorized') { 
      fb_oAuth(); 
      callBack(false); 
     } else { 
      fb_oAuth(); 
      callBack(false); 
     } 
    }, true); 
} 
+2

'FB.getLoginStatus'不返回一個值,它是一個「委託」調用。因此,在更改登錄文本之前,您需要重構代碼以等待Facebook響應。 – potench

+0

@potench你認爲我應該檢查我的按鈕點擊這個? 'response.status ==='connected'' –

+2

功能是正確的。此外,在var io = return fb_loginCheck();之後沒有執行任何操作,因爲你正在將函數告訴'return'。 – bfavaretto

回答

1

這樣的事情可能會奏效。我已經移動了這些方法,以便在從FB.getLoginStatus方法返回響應時它們被解僱。

我正在通過callBack方法,當FB.getLoginStatus的響應返回結果時會觸發該方法。另外請注意,我必須重新確定$(this)變量的範圍。

function fb_loginCheck(callBack){ 
    FB.getLoginStatus(function(response, e) { 
     if (response.status === 'connected') { 
      var uid = response.authResponse.userID; 
      var accessToken = response.authResponse.accessToken; 
      e.returnValue = true; 
      callBack(true); 
     } else if (response.status === 'not_authorized') { 
      // the user is logged in to Facebook, but has not authenticated your app 
      fb_oAuth(); 
      e.returnValue = false; 
      callBack(false); 
     } else { 
      // the user isn't logged in to Facebook. 
      fb_oAuth(); 
      e.returnValue = false; 
      callBack(false); 
     } 
    }, true); 
} 


$('.myBttn').click(function(){ 
    var targ = $(this); 

    fb_loginCheck(function (io) { 
     targ.text((io) ? "yes" : "no"); 
    }); 

    return false; 
}); 
+0

將'io'更新爲您的回調內部。在獲得Facebook響應之前,'fb_loginCheck'中的匿名函數將不會觸發。這不是構建正在發生的最明顯的方法,但它最接近您的原始代碼。讓我知道如果你需要更清楚地概述 – potench

+0

謝謝你,我2x檢查了我的代碼,但我沒有得到按鈕的響應點擊 –

+0

它似乎像匿名函數內的一切不被稱爲 –