Fez Vrasta
Fez Vrasta

Reputation: 14835

Function with function as parameter

I'm trying to define a function that should call a(nother) function that is passed as parameter of the main function.

function showMessage(title, text, button, callback) {

    console.log(title, text, button);

    if (typeof (callback) != "function") {
        function callback() {};
        alert("converted callback");
    }

    $("div").click( function() {
        callback();
    });

}

function myfunction() {
    alert("function!");
}

showMessage("title", "text", "button", myfunction() );

Demo: http://jsfiddle.net/XvE8D/1/

The problem is that when showMessage() function is called, myfunction() is called istantly.

How can I fix the problem?

Upvotes: 1

Views: 76

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149108

As you've observed, myfunction() with parentheses invokes myfunction.

Try passing myfunction to showMessage without parentheses:

showMessage("title", "text", "button", myfunction);

Also, in showMessage you'll have to change this part:

if (typeof (callback) != "function") {
    function callback() {};
    alert("converted callback");
}

To this:

if (typeof (callback) != "function") {
    callback = function() {};
    alert("converted callback");
}

To pass additional parameters to myfunction, you can wrap myfunction in another function and pass that to showMessage. Something like this should work:

showMessage("title", "text", "button", function() { myfunction('foo'); });

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388446

You need to pass a function reference as the callback argument, in your case you are invoking the function and is assigning the value returned by myfunction(in this case undefined) as the callback argument.

Also see the use $.noop()

function showMessage(title, text, button, callback) {   
    console.log(title, text, button);

    callback = callback || $.noop;

    $("div").click(function(){
        callback('my params')
    });
}

function myfunction() {
    alert("function!");
}

showMessage("title", "text", "button", myfunction);

Upvotes: 2

Related Questions