This question already has an answer here:
This question looks like a duplicate, as the title is nearly replicated. But, my issue seems simpler and I can't find the answer to it.
I have a Javascript function that executes another callback function, it works like this:
<script type='text/javascript'>
firstfunction(callbackfunction);
</script>
where callback function is defined as:
callbackfunction(response) {
if (response=='loggedin'){
// ... do stuff
}}
but I want it to be something like this:
callbackfunction(response, param) {
if (response=='loggedin'){
// ... do stuff with param
}}
My question is, does it work to pass the parameter like this:
<script type='text/javascript'>
firstfunction(callbackfunction(param));
</script>
or am I doing it wrong?
Use an anonymous function:
Adding parameters when calling a function. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply
xdaz already answered the simple version. Here is an example with variable amount of parameters.
In direct answer to your question, this does not work:
That will execute
callbackfunction
immediately and pass the return value from executing it as the argument tofirstfunction
which is unlikely what you want.It is unclear from your question whether you should just change
firstfunction()
to pass two parameters tocallbackfunction()
when it calls the callback or whether you should make an anonymous function that calls the callback function with arguments.These two options would look like this:
or
function
is key word, you can't use it as function name.Let say your function name is
foo
, then you could do like below:I think this is what you're looking for.
Lets say you're using jQuery ajax to do something, and you're passing it named callbacks. Here we have an onError callback that you might use to log or handle errors in your application. It conforms to the jQuery Ajax error callback signature, except for an extra parameter that you might have wanted to add at the back
this is where your function would be called - but you want an extra parameter
So this is what you can do to add the extra parameter
arguments
is an array in JavaScript that contains all arguments passed to a function, and so you're just passing those arguments along to the callback.Arguments
Bind