如何传递额外的参数回调和访问默认参数? [英] How to pass additional arguments to callbacks and also access default parameters?
问题描述
假设我有一个jQuery小部件的选项:
Suppose I have this as an option to a jQuery widget:
function oneFunc()
{
var myVar;
//there is some widget calling
$.widget("ui.combobox", $.ui.autocomplete, {
options: {
source: function (request, response){////doing something with myVar, request and response}
}
});
}
现在我想分离出 ,response)
使用回调
所以,我想要这样的:
function oneFunc()
{
var myVar;
//there is some widget calling
$.widget("ui.combobox", $.ui.autocomplete, {
options: {
source: myCallBack
});
}
function myCallBack(request, response){
//I can get request and response here by default but not myVar
//doing something with myVar, request and response
}
因此,我无法访问myVar。我必须把它传递给那里。但是怎么做呢?
So, I can't access myVar. I have to pass it there. but how to do that?
EDIT:
我不想使用全局变量
code>,
response
是我可以在myCallBack中获得的默认值。
I don't want to use global variables
request
, response
are default values that I can get in myCallBack anyway.
推荐答案
如果您要访问 myVar
分离的回调函数,我将在声明中明确:
If you want to access myVar
inside your separated callback function, I would make it explicit in the declaration:
function myCallBack(request, response, myVar)
{
}
这样可以更方便地跟踪您在代码中看到它的时间稍后的。然后,你写这样的代理函数:
This makes it easier to keep track of when you see it in your code later on. Then, you write a proxy function like this:
source: function(request, response) {
return myCallBack.call(this, request, response, myVar);
}
如果您需要更复杂的范围或 myVar
需要在两个范围内更改,您需要一个对象:
If you want a more complex scope or myVar
needs to be changed in both scopes, you need an object:
var myScope = {
myVar: null
};
// ...
source: function(request, response) {
return myCallBack.call(this, request, response, myScope);
}
然后,在回调内:
function myCallBack(request, response, myScope)
{
// use myVar as myScope.myVar
}
这篇关于如何传递额外的参数回调和访问默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!