Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a user event [duplicate]

I'm developing a javascript class (with jQuery) to create custom popup, but I can not figure out how to "pause" the script to wait for user response (click on the OK button or cancel)

the class is like this:

function Popup()
{
}

Popup.Show = function(text)
{
    var _response;
    /* code to draw the popup elements*/

    $("#button-ok").on("click",function()
    {
        _response = "ok!"
    }

    return _response
}

if, for example, use it in an alert, the method always return "undefined", because it does not wait for user click

alert(Popup.Show("hello"))
//return undefined before the popup appears

I tried to use a while loop like this:

Popup.Show = function(text)
{
    var _response;
    var _wait = true;

    /* code to draw the window */

    $("#button-ok").on("click",function()
    {
        _wait = false;
        _response = "ok!"
    }

    while(_wait){};

    return _response
}

but does not work (as I expected)

Then, how do I wait for the user click?

Thanks to all

like image 255
Luca Avatar asked Nov 11 '22 20:11

Luca


1 Answers

JavaScript is asynchronous, you cannot "pauses" execution. Moreover, while javascript is running the entire user interface freezes, so the user cannot click the button.

Once you have registered the callback to the click event, the program continues its execution. The following lines in your script

    _wait = false;
    _response = "ok!"

will never get executed until the Popup.Show function returns. Perhaps this Nettuts article about javascript event programming will help you understand the paradigm.

Here is a try to fix your code :

Popup.Show = function(text)
{
  /* code to draw the window */

  // bind click event
  var myPopup = this;
  $("#button-ok").on("click",function()
  {
    // this code will be executed after Popup.Show has return
    myPopup.response = "ok!"
    myPopup.Close();
  }
}
like image 72
Fabien Quatravaux Avatar answered Nov 15 '22 04:11

Fabien Quatravaux