In everything I've read thus far, callback functions are passed as arguments into other functions:
function mycallback(){
//dosomething
}
function mainfunc(mycallback){
//do something else
mycallback();
}
mainfunc(mycallback);
Which works as you would expect, great. My question is if the passing of the callback function as an argument into the mainfunc is requried? It seems if you omit this:
function mycallback(){
//dosomething
}
function mainfunc(){
//do something else
mycallback();
}
mainfunc();
it works fine, and is identical to the first example. But I don't see people using callbacks in this way. Is there a reason? What am I missing?
You second approach works fine if you want a single function to handle all callbacks.
Often when you call a method that uses a callback, you want it to different things in the callback depending on when you call it and from where. Instead of handling all different situations in a single callback function (which then has to be aware of which situation it is), you can simply use one callback function for each specific situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With