I'm new to ajax and callback functions, please forgive me if i get the concepts all wrong.
Problem: Could i send a callbackfunction as a parameter to another function that will execute the callback?
function firstFunction(){
//some code
//a callback function is written for $.post() to execute
secondFunction("var1","var2",callbackfunction);
}
function secondFunction(var1, var2, callbackfunction) {
params={}
if (event != null) params = event + '&' + $(form).serialize();
// $.post() will execute the callback function
$.post(form.action,params, callbackfunction);
}
Yes of course, function are objects and can be passed, but of course you must declare it:
an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).
Example for
CoffeeScript
:Yup. Function references are just like any other object reference, you can pass them around to your heart's content.
Here's a more concrete example:
You can also pass in arguments for
foo
:If you google for
javascript callback function example
you will get Getting a better understanding of callback functions in JavaScriptThis is how to do a callback function:
Also, could be simple as: