user3530437
user3530437

Reputation: 89

about java script variable scope and facebook api

I am using facebook login api to get user information, code can exceed correctly and FirstName can get from facebook api, but the first alert has correct value, the second value is still "". First I think it is because remote call time cause the second alert is before the first alert, after I using a delay function before second alert, also I can not get value in the second alert.

Part of code like below.

if (response.status === 'connected') {

        FirstName="";
        LastName="";
        FB.api('/me', function(response) {
            FirstName  = response.first_name;
            LastName  = response.last_name;
            Email  = response.email;
            alert(FirstName);
         });

         alert(FirstName);

}

Upvotes: 0

Views: 136

Answers (1)

Jurion
Jurion

Reputation: 1298

FB.Api is asynchronies method, which will post/get to a remote server. The execution don’t wait for it to finish before your second “alert” The only way you can be sure your FirstName is initialized, is using callbacks or MVVM pattern. Here MVVM with knockout.js code:

var fbModel = function () {
    var self = this;
    self.FirstName = ko.observable("");

    self.FirstName.subscribe(function () {
        //DO what you want, first name just been changed from FB
    });

    self.load = function () {
        FB.api('/me', function (response) {
            self.FirstName(response.first_name); // WILL TRIGGER self.FirstName.subscribe
        });
    };

};

And don’t forget, applying this model is easy, I can give you some links if you want. (But just go and look on examples on their site)

Edit : callback version

var FirstName = ""; // Global


function callback(name) {
    //your name has been loaded
    FirstName = name; // Global is initialized
};



function load (callback) {
    FB.api('/me', function (response) {
        callback(response.first_name);
    });
};


//Now just call the load : 

load(callback);

Upvotes: 1

Related Questions