Question

This is a simple question. Here is my code:

$(document).ready( function () {

    func1( "foo", callback);

    function callback(param){
        alert(param+" is my name");
    }

    function func1(name, cb) {
        cb(name);        // alerts "foo is my name"
        callback("bar"); // alerts "bar is my name"
    }
});

I want to know:

  • Which one of the function calls inside func1 is the correct callback and why?
  • Or are they both correct?
  • Isn't callback("bar"); a normal function call?
Was it helpful?

Solution

Callbacks are meant to let a caller specify what a function should do at some defined point in that function's execution. The function being called shouldn't know the name of that callback function ahead of time. So they'll often be passed to a function as an argument and the function that's supposed to call the callback should just invoke that argument.

When you call callback("bar") in func1, you're totally missing the point of callbacks. You may be invoking the function that you happen to use as a callback, but the point of callbacks is that func1 isn't supposed to know about that. It's just supposed to call the function that's been passed in as an argument (cb). When I'm calling func1 I should be able to pass a completely different callback function and func1 should just call that function without knowing what its name is (it may not even have one!).

The "correct" way is cb(name).

OTHER TIPS

callback("bar"); is directly invoking the callback function where as cb(name); calls the reference passed to the func1,

cb(name); seems to be the correct way here.

First one. Function calls another one which has been pased as a parameter.

It seems like most jquery methods follow this this form for callbacks:

 $(SUBJECT).method(function() {
     //do stuff
 }, /*callback here*/ function(){
    //do stuff
 });

like for instance

$(foo).click(function() {
      $(bar).fadeIn(300, function(){
         //call back here
      });
 });

fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top