Search code examples
javascriptjquerycallbackjquery-callback

Is this a correct way of JavaScript/jQuery callback?


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?

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).