Overriding Javascript Confirm() while preserving the callback

半城伤御伤魂 提交于 2019-12-21 12:51:51

问题



To the point, I want to override the standard js confirm() function within a jQuery plugin. I have figured out how to do it with the simple function layout below.

function confirm(opts) {
   //code
}

Now, what I want to do is call another function within the confirm function above, like so...

function confirm(opts) {
   openModal(opts);
}

The openModal function will open a custom modal window with the message and required buttons. The buttons are both <span> with the id of either submit or cancel. submit returns true and cancel returns false. But now, how do I return either true or false based on the button clicked?

For example...

$('#openModal').live('click', function() {
   var opts = { title:'Modal Title', message:'This is a modal!' };
   var resp = confirm(opts);
   if(resp) 
      // user clicked <span id="submit"></span>
   else 
      // user clicked <span id="cancel"></span>
});

Hopefully you understand what I mean.


回答1:


This is possible but not exactly as you describe. The typical way the confirm function is used is:

if(confirm("Are you sure you want to submit this form?")) {
    form.submit();
}

In the above example, the button press is returned synchronously to the script. Execution is paused within the function until a button is pressed.

A "modal dialog" is just an overlay over the entire contents of an HTML web page. To the browser, buttons within such an overlay work the same way as buttons anywhere else within that page do.

Since JavaScript handles such button clicks asynchronously (i.e. using callback functions to handle events) rather than synchronously, the approach you are attempting will not work.

You would need to change all parts of the code that use the confirm function to look like this:

confirm("Are you sure you want to submit this form?", function(result) {
    if(result) {
        form.submit();
    }
});

This would work just as registering an event handler with jQuery itself does. Script execution continues immediately, skipping past all the code in the anonymous function. Later, the browser will call that function indirectly through a JavaScript event handler that you register within the confirm function, its purpose to call the callback function with either true or false as appropriate.



来源:https://stackoverflow.com/questions/3886228/overriding-javascript-confirm-while-preserving-the-callback

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