开发者

Context on facebook api callback?

开发者 https://www.devze.com 2023-01-17 12:31 出处:网络
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, be

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


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


Edit: This is only part of the solution. Apply() can be used with closures to return a function that is bound to an object's scope (see Jamie's post).

Ex:

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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消