Tom
Tom

Reputation: 12669

Losing scope in an asynchronous call to facebook api

for (var i = 0; i < friends.length; i++) {
    var friend = $("<li>" + friends[i].name + "</li>");
    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, function (response) {
        //friend here is the last one created for all callbacks
    });
}

I have a loop which invites friends to an event, I am finding the the jquery friend object created here is always the last one created for all callbacks. I am assuming this is because the Facebook call is asynchronous. How would I be able to maintain scope here?

Upvotes: 0

Views: 177

Answers (2)

Guffa
Guffa

Reputation: 700582

You can create a closure for the local variable:

for (var i = 0; i < friends.length; i++) {
  var friend = $("<li>" + friends[i].name + "</li>");

  (function(friend){

    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, function (response) {
      //friend here is the parameter in the closure, so it's preserved for each item
    });

  })(friend);

}

Upvotes: 2

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26719

Try this:

for (var i = 0; i < friends.length; i++) {
    var friend = $("<li>" + friends[i].name + "</li>");
    var callback = (function(friend){
       return function (response) {
          //friend here should be the correct one
       })(friend);
    }
    FB.api('/' + eventId + '/invited/' + friends[i].id, 'post', {}, callback);
}

Upvotes: 1

Related Questions