0

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:

$("#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.

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks for the link, that post is great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.