简体   繁体   English

如何在facebook init函数javascript中设置标志?

[英]How to set flag in facebook init function javascript?

I have a sample code: 我有一个示例代码:

function initFB() {
    var flag;
    window.fbAsyncInit = function() {
        FB.init({appId: 'zzzzzz', status: true, cookie: true, xfbml: true});

        var flag;
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                flag = 1;
            } else if (response.status === 'not_authorized') {
                flag = 2;
            } else {
                flag = 3;
            }
        });    
    };
    return flag;
}

var flag = initFB();
alert(flag); 

=> result is undefined , Can't set flag in facebook function ?, If not, how to fix it ? =>结果是undefined ,无法在facebook功能中设置标志?,如果没有,如何解决?

What I would suggest you to do is to use a callback (probably anonymous), as the functions fbAsyncInit and getLoginStatus functions are both asynchronous (which means that they won't return something right away - they have to call facebook first, and after they've done so, they call their own callback (the function() { part)). 我建议你做的是使用回调(可能是匿名的),因为函数fbAsyncInitgetLoginStatus函数都是异步的(这意味着它们不会立即返回 - 他们必须首先调用facebook,然后再调用它们他们这样做了,他们称自己的回调( function() {部分))。

function initFB(callback) {
    window.fbAsyncInit = function() {
        FB.init({appId: 'zzzzzz', status: true, cookie: true, xfbml: true});

        FB.getLoginStatus(function(response) {
            var flag;
            if (response.status === 'connected') {
                flag = 1;
            } else if (response.status === 'not_authorized') {
                flag = 2;
            } else {
                flag = 3;
            }
            callback(flag);
            /* This will call the anonymous function specified as 
               "callback" with a parameter of whatever is in the 
               "flag" variable. */
        });    
    };
}

/* Here we use an anonymous function as a callback of 
   when getLoginStatus has gotten it's return value */
initFB(function(flag) {
    alert(flag); 
});

That is a scope and sync problem. 这是范围和同步问题。 The second time you define "flag" it´s only visible inside of the fbAsyncInit function, no connection to the "flag" variable on the outside. 第二次定义“flag”时它只在fbAsyncInit函数内部可见,没有连接到外部的“flag”变量。 Also, the code in the fbAsyncInit function will get called later, when "flag" on the outside already got returned. 此外,当外部的“flag”已经返回时,fbAsyncInit函数中的代码将被稍后调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM