如何在window.fbAsyncInit外调用FB.api

lin*_*man 4 facebook facebook-javascript-sdk

所以我有fb api初始化

window.fbAsyncInit = function() {
        FB.init({
          appId  : '351808841561163',
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true,  // parse XFBML
          oauth: true
        });
Run Code Online (Sandbox Code Playgroud)

我有一个单独的带有函数的js文件:

function example(){
  FB.api(
    '/me/[namespace]:visit',
    'post',
    { channel: link},
    function(response) {
       if (!response || response.error) {
          console.log(response.error);
       } else {
          console.log('Follow was success! Action ID: ' + response);
       }
    });
 }
Run Code Online (Sandbox Code Playgroud)

当我打电话给我时,我得到的FB是未定义的.

当我把函数放在window.fbAsyncInit里面时它工作正常,但我需要在window.fbAsyncInit之外调用FB.

如果有可能的方法吗?

小智 12

只需对您的函数进行排队,然后在FB初始化后立即调用它.下面的代码保证您的函数将按正确的顺序调用,并在FB完成初始化后立即调用

在您的示例之前和FB init脚本之前包含的帮助程序脚本:

var FB; // to avoid error "undeclared variable", until FB got initialized
var myQueue = new Array();
function queueAdd(f){
  if (FB == undefined)
    myQueue.push(f);
  else
    f();
}

function processQueue(){
  var f;
  while(f = myQueue.shift())
    f();
}
Run Code Online (Sandbox Code Playgroud)

你的函数示例:

function example(){
  FB.api(
    '/me/[namespace]:visit',
    'post',
    { channel: link},
    function(response) {
       if (!response || response.error) {
          console.log(response.error);
       } else {
          console.log('Follow was success! Action ID: ' + response);
       }
    });
 }

queueAdd(example); // will run immediately if FB initialized. Otherwise, wait for FB first
Run Code Online (Sandbox Code Playgroud)

和FB部分:

window.fbAsyncInit = function() {
  FB.init(blablabla);
  processQueue();
}
Run Code Online (Sandbox Code Playgroud)