Wait for a user event [duplicate]

不羁岁月 提交于 2019-11-29 15:21:54

This is a typical JavaScript issue.

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

return _response

Now let's see what happens here. You're setting an onClick listener to the button, and assign a callback function for that event. Think of that function as of an argument you pass to another function. It is not executed directly.

Now instead of using something like while(_wait){}; and force it to execute synchronous, you should work with that callback.

 Popup.Show = function(text)
 {

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

 };

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

This is a nice start into callbacks: http://javascriptissexy.com/

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

The context of what you are trying to do and why is a little vauge since it seems like you are trying to rebuild the 'alert' function. But 'alert' is a window function that is set up by the browser. This question seems like a duplicate of Stop page execution like the alert() function

Which basically talks about callback chaining, essentially encapsulating functionality so you can enforce the order in which they run. I also think you have a fundamental misunderstanding of how the code is run. As discussed event handlers are asynchronous and while the code is read in order, it is not going to run the function set within the event hanlders callback until that event has been triggered.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!