Context on facebook api callback?

Is there any way to pass context in javascript facebook sdk api callback? Here is a simple example. Now this will not work, because the variable 'this.name' in my callback function will be undefined, because it is not in my context of custom objects. Any idea how to do this?

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');
+3
source share
2 answers

Edit: this is only part of the solution. Apply () can be used with closure to return a function associated with the area of ​​the object (see Jamie's Post).

Example:

function bindScope = function(context, obj)
{
    return function()
    {
        return obj.apply(context);
    }
}

I believe you can change the context using javascript apply (). Try changing line # 8 to callback.apply (this).

- http://kossovsky.net/index.php/2009/07/function-context-and-apply-function/

+1

- .

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');
+3

Source: https://habr.com/ru/post/1765828/


All Articles