Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context on facebook api callback?

Is there a way to pass context in a javascript facebook sdk api callback? Here's a simple exemple. Now this won't work because the variable 'this.name' in my callback function would be undefined, because it's not in my user object context. Any idea how to do it?

function user(id) {
 this.id = id;
 this.getUserName = function(fields,callback){
   FB.api({
     method:'fql.query',
     query: 'SELECT '+ fields.toString() +' FROM profile WHERE id=' + this.id
     },
     callback
   );
 }
 this.getUserName(['name'],function(response){this.name = response[0].name;});
}

var  amigo = new user('fb_id_here');
like image 376
plehoux Avatar asked Dec 17 '25 19:12

plehoux


1 Answers

Closures are your friend.

function user(id) {
 this.id = id;
 this.getUserName = function(fields,callback){
   FB.api({
     method:'fql.query',
     query: 'SELECT '+ fields.toString() +' FROM profile WHERE id=' + this.id
     },
     callback
   );
 }
 this.getUserName(['name'],(function(this_user) {
   return function(response){this_user.name = response[0].name;}
 })(this));
}

var  amigo = new user('fb_id_here');
like image 134
Jamie Wong Avatar answered Dec 19 '25 08:12

Jamie Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!