2010-09-16 74 views
2

这不是一个jQuery的问题。创建一个回调函数并将它连接起来

我想创建一个回调函数...所以用户会使用它像这样:

myfunc.init('id',{option1: val, option2: val2}, function() { 

//in here users can now call methods of myfunc 

}); 

如何做到这一点我的代码中。操作系统一旦我知道我的脚本已经准备就绪,我想能够以某种方式调用这个匿名函数。

希望这是有道理的。我经常不会。

回答

2

你可以写这样的:

var myfunc.init(id, options, callbackFunction){ 

//do whatever you want with id & options 

callbackFunction(); 

} 

这将首先运行一切你想在你的init函数中运行提供的函数作为回调参数

+0

当然,我在脑海中过度复杂化 – 2010-09-16 12:07:47

2

事情是这样的:

var myfunc.init = function(id, options, func) { 
    // call func somewhere at some point 
    func(); 
}; 

通常回调的使用,因为你想在某个时间点调用它是未知的(非同步)...像例如,当一个AJAX请求完成:

var myfunc.init = function(id, options, func) { 
    myAjaxRequest("url.com", function() { 
     // call the func at this point in time 
     func(); 
    }); 
}; 
+0

THanks,我在等待YouTube的api告诉我玩家已经准备好了。那时我想让用户提示新视频/移位播放头等。 – 2010-09-16 12:08:31

相关问题