2011-02-24 129 views
5

我想知道如何实现回调到这段代码创建一个Javascript回调函数?

MyClass.myMethod("sth.", myCallback); 
function myCallback() { // do sth }; 

var MyClass = { 

myMethod : function(params, callback) { 

    // do some stuff 

    FB.method: 'sth.', 
     'perms': 'sth.' 
     'display': 'iframe' 
     }, 
     function(response) { 

      if (response.perms != null) { 
       // How to pass response to callback ? 
      } else { 
       // How to pass response to callback ? 
      } 
     }); 
} 

}

回答

6

所有你需要做的就是调用回调函数以正常的方式。在这种情况下,你只需要做callback(response)

var MyClass = { 

myMethod : function(params, callback) { 

// do some stuff 

FB.method: { 'sth.', 
    'perms': 'sth.' 
    'display': 'iframe' 
    }, 
    function(response) { 

     if (response.perms != null) { 
      // How to pass response to callback ? 
      // Easy as: 
      callback(response); 
     } else { 
      // How to pass response to callback ? 
      // Again: 
      callback(response); 
     } 
    }); 
} 

} 
+0

太容易了。谢谢 – fabian

+0

没问题。 :)随意将其标记为答案。 –

-3
 

var callback = function() { 

}; 

完蛋了:-)

+0

那岂不是'回调(响应)'? – mellamokb

+0

Sry,我没有明白吗? – fabian

+2

这似乎没有任何关系的问题。 –

1

只需调用中传递功能。

callback(response) 
-1

现在你已经有了一个函数的引用。只需调用它:

callback(response.perms); 
1

我想你可以简单地在那里拨打callback(response.perms)。你也可以把它注册为你的类的

成员:

MyClass.cb = callback; 

后来称之为:

MyClass.cb(response.perms) 
0
callback.call(null, response); 
1

你靠近...只是使用回调。在这种情况下,你可以形成一个闭包。

var MyClass = { 

myMethod : function(params, callback) { 

    // do some stuff 

    FB.method: 'sth.', 
     'perms': 'sth.' 
     'display': 'iframe' 
     }, 
     function(response) { 

      if (response.perms != null) { 
       callback(response); 
      } else { 
       // response is null, but you can pass it the same as you did above - if you want to. Probably better to have a generic failure handler 
       ajaxFailHandler(); 
      } 
     }); 
} 
0
MyClass.myMethod("sth.", myCallback); 
var myCallback = function myCallback() { // do sth } 

var MyClass = { 

myMethod : function(params, callback) { 

    // do some stuff 

    FB.method: 'sth.', 
     'perms': 'sth.' 
     'display': 'iframe' 
     }, 
     function(response) { 

      if (response.perms != null) { 
       callback(); 
      } else { 
       callback(); 
      } 
     }); 
} 

} 
+1

不知道你为什么发布这个......但你没有将'response'变量传递给你的回调函数。 '回调(回应);'会做的伎俩 - 正如其他答案所示。 –

13

三种方式实现 “//如何通过响应回调?” :

  1. callback(response, otherArg1, otherArg2);
  2. callback.call(this, response, otherArg1, otherArg2);
  3. callback.apply(this, [response, otherArg1, otherArg2]);

1是最简单的,2是如果你想控制你的callbackFunction参数里面的 'this' 变量的值,和3类似于2,但您可以将可变数量的参数传递给callback

这里是一个不错的参考:http://odetocode.com/Blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

+0

非常完整的答案...很好! –

相关问题