- Jan 2, 2006
- 10,455
- 35
- 91
I'm still a bit befuddled with callbacks.
Callback: a function that is run after the main function has finished running.
So if I'm writing a custom function with the option for a callback, I have to:
1. specify it as a parameter
2. do a check and make sure that the parameter passed in from the user is actually a function
3. run the callback at the very end of my code block
When I'm actually running the function, I just pass in the other parameters like normal, but I type in the actual function code as the last parameter.
Obviously this won't work if the callback function I want is a big function and requires multiple parameters.
So how do I define or run my original function if my callback function is really large?
How do I run this callback inside of the mySandwich function?
If I do:
The superLongCallBackFunction will run FIRST because (I think) as JS parses through the parameters, it simple runs superLongCallbackFunction("lala", "hihi", "lol") when it gets to it.
Callback: a function that is run after the main function has finished running.
Code:
var mySandwich = function(param1, param2, callback) {
alert('Started eating my sandwich. It has: ' + param1 + ', ' + param2);
if (callback && typeof(callback) === "function") {
callback();
}
}
mySandwich('ham', 'cheese', 'vegetables'); // code will only alert ham and cheese.
mySandwich('ham', 'cheese', function(){ alert("hello"); }); // will alert ham and cheese and then alert a second time hello
So if I'm writing a custom function with the option for a callback, I have to:
1. specify it as a parameter
2. do a check and make sure that the parameter passed in from the user is actually a function
3. run the callback at the very end of my code block
When I'm actually running the function, I just pass in the other parameters like normal, but I type in the actual function code as the last parameter.
Obviously this won't work if the callback function I want is a big function and requires multiple parameters.
So how do I define or run my original function if my callback function is really large?
Code:
var mySandwich = function(param1, param2, callback) {
alert('Started eating my sandwich. It has: ' + param1 + ', ' + param2);
if (callback && typeof(callback) === "function") {
callback();
}
}
var superLongCallbackFunction = function(param1, param2, param3){
// a billion lines of code
};
How do I run this callback inside of the mySandwich function?
If I do:
Code:
mySandwich("tuna", "mayo", superLongCallbackFunction("lala", "hihi", "lol"));
The superLongCallBackFunction will run FIRST because (I think) as JS parses through the parameters, it simple runs superLongCallbackFunction("lala", "hihi", "lol") when it gets to it.
Last edited:
