Reputation: 723
This is my code
function confirm(){
okBtn.on('click', function(){
// return true from confirm function
});
cancelBtn.on('click', function(){
// return false from confirm function
});
}
if(confirm()){
// make something. I need to keep this code here, not in confirm function
}
I need to execute callback after okBtn or cancelBtn are clicked. I need to keep callback code not in function, coz I have a lot of cases that use this function.
Upvotes: 2
Views: 10618
Reputation: 5908
Instead of using an extra function, you could simply create a flag and change it based on user action:
var confirm_flag; // this is undefined, which means that no actions have been taken
okBtn.on('click', function(){
validate(true);
});
cancelBtn.on('click', function(){
validate(false);
});
Then, based on the user input, you can determine which course of action you want to take:
function validate(flag) {
if(flag) {
alert("okBtn has been clicked, it's safe to continue");
}else{
alert("Not good!");
}
}
If you want to use the return value from a confirm popup, you can simply assign the Window confirm()
function to a variable - if the user clicks ok, it will return true
var x = confirm('Is it safe?'); // will pop a confirm dialog box and return true if ok is pressed and false if cancel is pressed
Upvotes: 1
Reputation: 528
As per my understanding what you want is to execute some code only when the user click on the okBtn and some code when the user click on cancelBtn. If that you can change your code in this way
function confirm(callback)
{
okBtn.on('click', function(){
// return true to the callback
callback(true)
});
cancelBtn.on('click', function(){
// return false to the callback
callback(false)
});
}
confirm(function(confirmed){
if(confirmed)
{
// make something
}
else
{
// do something
}
});
Upvotes: -2
Reputation: 816262
Make the confirm
function accept the callback and invoke it inside the event handlers:
function confirm(callback){
okBtn.on('click', function(){
callback(true);
});
cancelBtn.on('click', function(){
callback(false);
});
}
confirm(function(result) {
// make something. I need to keep this code here, not in confirm function
});
But there is no way to deal with event handlers synchronously (like you seem intend to do). The very reason why you have to bind event handlers is that you don't know when the events occur. Instead you have to react to the event. You have to get used to this way of coding, there is no way around.
Upvotes: 5
Reputation: 369
html
<button type="button" id='button1'>confirm</button>
<button type="button" id='button2'>cancel</button>
js
$('#button1').click(function(){
confirm(true);
});
$('#button2').click(function(){
confirm(false);
});
function confirm(check){
if(check){
alert('ok');
}else{
alert('cancel');
}
}
I did a small sample for you. You can either write your code inside the if condition or call another function if your function is really long
Upvotes: 0