Waiting for custom event

I am developing a javascript class (with jQuery) to create a custom popup, but I can’t figure out how to “pause” the script to wait for the user to respond (click OK or cancel)

the class is as follows:

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, you use it in a warning, the method always returns "undefined" because it does not wait for a button to be pressed

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

I tried using the while loop as follows:

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 to wait for the user to click?

Thank you all

+3
source share
3 answers

This is a typical JavaScript problem.

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

return _response

, . onClick . , . .

, - while(_wait){}; , .

 Popup.Show = function(text)
 {

    $("#button-ok").on("click",function()
    {
           drawSomething('ok');
    }

 };

var drawSomthing = function(response) {
 // do something
 };

: http://javascriptissexy.com/

0

JavaScript , "" . , javascript , .

click, . script

    _wait = false;
    _response = "ok!"

, Popup.Show . , Nettuts javascript .

:

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();
  }
}
0

, , , "alert". "alert" - , . , alert()

, , , . , , . , , , , , hanlders , , .

0

Source: https://habr.com/ru/post/1615826/


All Articles