开发者

Specifying parameters when creating a jQuery callback

开发者 https://www.devze.com 2023-03-30 12:35 出处:网络
I\'m writing a jQuery plugin and I\'m trying to set up a callback that takes a few parameters. How does jQuery determine which parameters are to be sent to a callback function?

I'm writing a jQuery plugin and I'm trying to set up a callback that takes a few parameters. How does jQuery determine which parameters are to be sent to a callback function?

In the plugin:

if (callback) {
    callback.call(var1, var2, var3);
}

The written callback:

开发者_JS百科
$("#div").myplugin({callback: myfunction});
myfunction(biz,bar,bim) {
    alert("I love " + biz + " and " + bar + " and " + bim);
}

biz is set to var2, bar is set to var3, and bim is undefined.


The first argument of the call function is special:

fun.call(thisArg[, arg1[, arg2[, ...]]])

where thisArg is

The value of this provided for the call to fun.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

So, it would work if you passed a value for thisArg:

callback.call(this, var1, var2, var3);

Or, more simply, don't use call at all if you don't need this in the callback:

callback(var1, var2, var3);


I believe you'll find the answer in this post.

Basically there are several ways of achieving the goal you want. If you look down the post to the last example, you have an args.push(arguments[i]); line that may pass several parameters to the function using the only two arguments for the apply call.

As said here, the call method is similar, you have to put all the function arguments in the second parameter of the call method.

0

精彩评论

暂无评论...
验证码 换一张
取 消