Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is passing a javascript callback function as a parameter required?

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?

like image 862
Ryan Ogle Avatar asked May 26 '26 01:05

Ryan Ogle


1 Answers

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.

like image 175
Guffa Avatar answered May 27 '26 15:05

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!