I am currentl开发者_如何学Cy working on developing custom dialog box to be used with my application using jQuery. The problem is that the call to create dialog is asynchronous i.e. the line of code after it is executed before it is displayed. Here is what I have done, I have created a function DisplayConfirm() which when called creates a modal dialog. I want to use it like the following:
if(DisplayConfirm()){
//do this
else
// do that
But I cannot because the line of code written after DisplayConfirm() is executed before the dialog is even created. How can I synchronize this operation so that I don't have to use callback functions?
Why do you want to avoid callbacks? They are neat :)
function displayConfirm(confirmStr, okCallback, cancelCallback) {
$('<div class=alert />')
.append('<p>' + confirmStr + '</p>')
.append('<button class=ok-btn>Ok</button>')
.append('<button class=cancel-btn>Cancel</button>')
.appendTo(document.body)
.delegate('.ok-btn', 'click', function (e) {
okCallback(e);
})
.delegate('.cancel-btn', 'click', function (e) {
cancelCallback(e);
});
}
There! You see, not too bad :)
Note: I wrote this just from the top of my head. Haven't tested it.
Edit: If this isn't clear enough, what I am suggesting here is that you have to use callbacks unless you want to use the native confirm
function, just as @PaulPRO stated in a comment to the question.
Once the displayConfirm
function is defined as above, you could use it with callbacks like so,
displayConfirm('Are you sure?', function (e) {
// do if confirmed
}, function (e) {
// do if not confirmed
});
I wanted to illustrate that it is indeed not too difficult to write a simple callback like functionality and you should be doing this.
Let me know if it still isn't clear.
You cannot write a function in javascript that interacts with the user and blocks the javascript interpreter. confirm
can do that because it is a browser built-in, written in C++ (or whatever).
use alternative option, create one function of your that executed after User generate some event. and call into a dialog box event, that give you to same beheviour.
ex. $("#dialog-modal").dialog({ resizable: false, width: 350, modal: true, buttons: [{ text:"OK", width:80, height:26, click: function() { $(this).dialog("close"); } } ] });
精彩评论