Rodrigo Calix
Rodrigo Calix

Reputation: 637

Javascript - Return in a function parameter another function

What i'm trying to do might sound simple.

I just need to make a callback with another function Here is an example using jQuery.

(function ( $ ) {
    "use strict";
    var colors;

    colors = function(col){
        return col;
    };

    $(document).ready(function(){
        colors(function(){alert('Orange');});
    });
})(jQuery);

So when the document be ready, i need to send an alert that says 'Orange' but i want to do it by returning a function.

If you know another way to do it please let me know.

Upvotes: 0

Views: 40

Answers (1)

Barmar
Barmar

Reputation: 782508

To call a function, you have to put () after it. Since colors() returns the function, put () after the call to colors:

$(document).ready(function(){
    colors(function(){alert('Orange');})();
});

More generally, the way you deal with callbacks is something like:

callback = getCallback(args);
callback();

Upvotes: 3

Related Questions