如何将其他参数传递给回调并访问默认参数?

时间:2013-07-08 11:39:55

标签: javascript jquery callback

假设我将此作为jQuery小部件的选项:

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

现在我想使用回调

分离function (request, 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。我必须把它传递给那里。但是怎么做?

修改 我不想使用全局变量 requestresponse是我在myCallBack中可以获得的默认值。

如果可以避免使用匿名函数,那就更好了。

3 个答案:

答案 0 :(得分:2)

您可以使用Function.applyFunction.call

执行此操作
function oneFunc(myCallback)
{
     this.myVar = 1;
    var request = "request";
    var response = "response"
     //there is some widget calling
     myCallback.apply(this,[request,response]);
}

function callback(request, response){
   console.log(request);
    console.log(response);
    console.log(this.myVar);
}

oneFunc(callback);

以上输出

request
response
1

因为您已将this关键字委托给回调方法,允许它访问原始方法中声明的任何变量。

实例:http://jsfiddle.net/hFsCA/

注意apply行也可以替换为(Thanks @AlessandroVendruscolo)

myCallback.call(this,request,response);

不是因为它有太大差异 - 而是为了完整性!

将其重新包装回您的(现在更新的)示例中:

function oneFunc(callback)
{
   this.myVar = 1;
   var self = this;
   //there is some widget calling
   $.widget("ui.combobox", $.ui.autocomplete, {

            options: {
                 source: function (request, response){
                        callback.call(self,request,response);
                 }
            }
   });

}

答案 1 :(得分:2)

如果您想在分离的回调函数中访问myVar,我会在声明中明确说明:

function myCallBack(request, response, myVar) 
{
}

这使您可以更轻松地跟踪以后在代码中看到它的时间。然后,你编写一个像这样的代理函数:

source: function(request, response) {
    return myCallBack.call(this, request, response, myVar);
}

如果您想要更复杂的范围或需要在两个范围中更改myVar,您需要一个对象:

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
}

答案 2 :(得分:0)

如果jQuery在内部使用任何匿名函数,我不会这样做。但我解决了这个问题:

function oneFunc()
{
     var myVar;
     //there is some widget calling
        $.widget("ui.combobox", $.ui.autocomplete, {
                options: {
                       source: $.proxy(myCallBack, this, myVar)
       });
}

function myCallBack(myVar, request, response){
//I can access myVar, request and response
//doing something with myVar, request and response
}

其他有经验的人可以对此发表评论,我想。