Change the asynchronous jQuery Dialog to be synchronous?

前端 未结 7 1384
名媛妹妹
名媛妹妹 2020-12-05 04:12

Currently, I\'m working to replace \"alert\'/\"confirm\" with the jquery dialog.

But most of legacy codes is written in some asynchronous way, which make it

7条回答
  •  天命终不由人
    2020-12-05 05:06

    I'm not exactly sure what the motivation behind not using callbacks is so it is hard to judge what solution might satisfy your requirements, but another way to delay execution is through jQuery's "deferred" object.

    http://api.jquery.com/category/deferred-object/

    You could set up a function that opens the jquery dialog and add code that "waits" for dialog to close. This ends up working in a fairly similar way to a callback in the case you've laid out but here is an example:

        function confirm () {
            var defer = $.Deferred(); 
            $('
    Do you want to continue?
    ').dialog({ autoOpen: true, close: function () { $(this).dialog('destroy'); }, position: ['left', 'top'], title: 'Continue?', buttons: { "Yes": function() { defer.resolve("yes"); //on Yes click, end deferred state successfully with yes value $( this ).dialog( "close" ); }, "No": function() { defer.resolve("no"); //on No click end deferred successfully with no value $( this ).dialog( "close" ); } } }); return defer.promise(); //important to return the deferred promise } $(document).ready(function () { $('#prod_btn').click(function () { confirm().then(function (answer) {//then will run if Yes or No is clicked alert('run all my code on ' + answer); }); }); });

    Here it is working in jsFiddle: http://jsfiddle.net/FJMuJ/

提交回复
热议问题