views:

57

answers:

2

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');
+1  A: 

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');
Jamie Wong
I did not understand your code, but your advice of looking for closure led me to a good solution. tks.
plehoux
+1  A: 

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/

John Himmelman
`apply` can be used here, but not in the way you're explaining. He's passing callback to another function, _as_ a function. If you passed `callback.apply(this)` instead, you'd be passing the result of the invocation, not the function itself.
Jamie Wong
I strongly recommend against using `object` as a variable name, given that `Object` is a JavaScript built-in. While not technically wrong, it's fairly confusing. Also, this is semantically wrong. `apply` is a method of `functions`, not general objects.
Jamie Wong
tks it's the good solution. I'm using _.bind() method from underscore.js framework who is doing exactly what your code is doing.
plehoux