All the examples here seem to show how to declare it, but not how to use it. I think that's also why @Kiran had so many issues.
The trick is to declare the function which uses a callback:
function doThisFirst(someParameter, myCallbackFunction) {
// Do stuff first
alert('Doing stuff...');
// Now call the function passed in
myCallbackFunction(someParameter);
}
The someParameter
bit can be omitted if not required.
You can then use the callback as follows:
doThisFirst(1, myOtherFunction1);
doThisFirst(2, myOtherFunction2);
function myOtherFunction1(inputParam) {
alert('myOtherFunction1: ' + inputParam);
}
function myOtherFunction2(inputParam) {
alert('myOtherFunction2: ' + inputParam);
}
Note how the callback function is passed in and declared without quotes or brackets.
- If you use
doThisFirst(1, 'myOtherFunction1');
it will fail.
- If you use
doThisFirst(1, myOtherFunction3());
(I know there's no parameter input in this case) then it will call myOtherFunction3
first so you get unintended side effects.
myfunction("hello", function(arg1) { console.log(arg1); })
– Hexamerous