1

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?

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160

2 Answers2

5

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'); });
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • thanks but what if I need to pass params to the callback? Do I need to pass them first to the showMessage and then pass them to the callback? – Fez Vrasta Nov 07 '13 at 16:23
  • @FezVrasta That depends. Are the parameters to the callback known at the time you call `showMessage` or are they only known when the user clicks the element? – p.s.w.g Nov 07 '13 at 16:26
  • Thanks, I've used the $.noop from @Arun P Johny's answer and the rest from yours. – Fez Vrasta Nov 08 '13 at 08:00
2

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);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531