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
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With