views:

52

answers:

5

Based on the JavaScript example below, is there a way to pass a reference to function f to the promptForProceed function and have it conditionally executed in promptForProceed?

Could you also do this if the ffunction took some parameters (ie: f(a, b, c) { ... })?

function f() {
    //Do stuff..
}

function promptForProceed(myFunction) {  // <------ PASS FUNCTION AS PARAMETER
    $("#div-dialog-proceed").dialog({
        modal: true,
        buttons: {
            "Stay on current page": function () {
                $(this).dialog("close");
            },
            "Continue": function () {
                $(this).dialog("close");
                myFunction(); // <---------  CALL FUNCTION
            }
        }
    });
}

Update: Think I like the option of using an anonymous function parameter:

promptForProceed(function() { //Do stuff like call f(a,b,c) });
+2  A: 

of course you can. Functions are objects!

Gabi Purcaru
+2  A: 

Yes. Functions are first-class objects in JavaScript and can be passed as parameters.

In fact, your syntax is correct. It should work already :)

NullUserException
What if f took parameters? Could you pass `f(a,b,c)` to the `promptForProceed` function?
Marcus
@Marcus Where are the parameters coming from?
NullUserException
@Marcus yes. Javascript is pretty intuitive if you ask me
Gabi Purcaru
you would pass (f, a, b, c), and then call f(a, b, c)
Lou Franco
+2  A: 

Yes, but you should probably not name both of them f or it will be confusing what is going on. The line you called f() on is calling the parameter, not the function f (unless that's what you passed)

To pass parameters, pass promptForProceed(myFunction, a, b, c) and then call with myFunction(a, b, c)

Lou Franco
A: 
promptForProceed(f, f_parameter)

Then pass f_parameter to f()

Xaqron
@ edited version: pass an array of objects
Xaqron
A: 

Yes you can. What you have should work. Passing parameters in is fine too.

You should also look in to the call method of function which allows you to set the scope

myFunction.call(object);

The apply method allows you to pass arguments in as an array.

myFunction.apply([param1, param2]);

Also, you should understand 'closures' and how scope works when passing functions around like this. http://en.wikipedia.org/wiki/Closure_(computer_science)#JavaScript

Joony