Good day.
I have a question and a doubt, the detail is as follows:
I am making a custom popup message with two buttons "yes" and "no". What I am trying to do is that this popup returns a response true
or false
according to the button that is pressed.
I have a function that builds the popup for me and creates the events click
of these buttons, it also creates a variable where the function will return true
or false
. Now, the problem is that this popup is activated from the event clic
of a separate button, the event fires and the function that creates the popup is activated, but the event ends there.
When I click the popup buttons they fire their own events and the thread of the previous event is lost, but on the side of the event of the button that opened the popup there is a variable waiting for the response of the message but when the thread is lost it does nothing.
Is there a way to achieve this, to return to the click event of the button that created the popup to take the response from it or is it something that cannot be achieved.
I don't know if I understand myself, it's a bit complicated to explain that, and now imagine looking for help on this on the internet.
PS: I am doing this in JQuery.
$("#next-wizard").on("click", function(){
var div_active = $(".active");
if(validate_step(div_active)){
response_msg = msg_box_popup("¿cual es tu respuesta?");
if(response_msg == true){
//hago algo.
}else{
//hago algo tambien.
}
}
});
function msg_box_popup(txt_msg){
var response = true;
var msg_box = $(".msg-box");
msg_box.parent().removeClass("hidden");
msg_box.find(".text-msg .msg").html(txt_msg);
msg_box.find("#btn_accept").on("click",function(){
response = true;
msg_box.parent().addClass("hidden");
});
msg_box.find("#btn_deneg").on("click",function(){
response = false;
msg_box.parent().addClass("hidden");
});
return response;
}
Use callbacks or promises
Callbacks
This is the simplest solution
promises
For this you need a library like Q , bluebird or similar. Fortunately jQuery comes with a fairly simple implementation called Deferred Object that can help you.
Note: You might be tempted to use it
defer.reject
to signal when the user chose false but this is a bad idea as itreject
is designed as the error channel so if an exception occurs it may be hard to tell if the user chosefalse
or there is a mistake somewhere. Usingresolve(false)
simplifies the problem.Due to the asynchronous nature of javascript, it is not possible to get the value for response_msg.
These problems are solved using callbacks in the functions, so that when an event occurs, this callback is called.
Your code should be updated as follows:
However, passing callbacks can lead to various problems like Callback Hell . I recommend you read about
Promises
, which make the code much more readable.