Tom Rider
Tom Rider

Reputation: 2805

function calling from another function javascript

I have 2 functions. First contains Jquery-UI dialog and called from the Second function. Something like :

function First() {
    $('div').dialog({
        buttons: {
            "Ok": function () { /* code */
            }
        }
    });
}

function Second() {
    First();
    /* rest of this function code is depend upon the "Ok button" 
       function code */
}

Now my problem is that after calling function First the execution of script doesn't wait for dialog's Ok button press. Whats should i do, so that only after pressing the Ok button, the control return from the function First?

Upvotes: 0

Views: 144

Answers (3)

gaurang171
gaurang171

Reputation: 9080

    function First(waitTillOk) {
        $('div').dialog({
            buttons: {
                "Ok": function () { 
                      /* code */
                      if(typeof waitTillOk == "function"){
                        waitTillOk();
                      }
                }
            }
        });
    }

    function Second() {
        var waitTillOk = function(){
         /* rest of this function code is depend upon the "Ok button" 
           function code */
     }
     First(waitTilOk);
    }

Upvotes: 1

scessor
scessor

Reputation: 16115

Move from the function Second the part after calling First into a 2nd function (here called SecondOkHandler). Call First with a new parameter (this callback function) and in the function First on 'ok' call this:

function First(okCallback) {
    $('div').dialog({ 
        buttons : {
            "Ok" : okCallback
        }
    });
}

function Second () {
    First(SecondOkHandler);
}

function SecondOkHandler() {
    /* rest of this function code is depend upon the "Ok button" function code */
}

Also see this example.

=== UPDATE ===

To make it more complex, here a link to an example with more callbacks.

Upvotes: 2

Vinayak Phal
Vinayak Phal

Reputation: 8919

This is because you have given a parenthesis First() this will make a call to that function as soon as the parser encounter that line.

You can make use of the one of the 2 Javascript methods of calling the function apply or call. By using this your function will not execute as soon it is encounter.

Check out this reference http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

Try using this and let me know if it is not working.

Upvotes: 1

Related Questions