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?

1
  • It is called instantly because you are calling it. :) myfunction() <-- () says run! Commented Nov 7, 2013 at 16:30

2 Answers 2

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'); });
Sign up to request clarification or add additional context in comments.

3 Comments

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?
@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?
Thanks, I've used the $.noop from @Arun P Johny's answer and the rest from yours.
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);

2 Comments

What if I need to pass a parameter to myfunction?
Ok so I need to pass the params of the function as separated params of the showMessage function right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.