将函数分解为Jquery延迟或承诺

时间:2017-04-21 17:43:36

标签: jquery jquery-deferred

我有以下代码。一旦加载HTML页面,其他用于加载不同的子部分和绑定回调函数与按钮。你能告诉我如何将两个ajax调用分解为promise并且一旦成功,那么只将事件绑定到按钮

function loadHtml(methodargs){

    header=methodargs.header;
    htmlname=methodargs.htmlname;
    subsection=methodargs.subsection;
    callbackfunction=methodargs.callbackfunction;
    buttonfunctioanlities = methodargs.buttons;


    $("#mainContentSubmit").off('click');
    $('#maincontentbody').empty();

    $("#maincontentheader").html(header);

    //Function 1
    if(htmlname != '')
       $( "#maincontentbody" ).load( ctx+"/loadpage?pagename="+htmlname, function( response, status, xhr ) {
          if ( status != "error" ) {
                $.each(callbackfunction, function( index, value ) {
                    window[value]();
                });
          }
        });

    //Function 2
    $.each(subsection,function(index,value){
        var data = {
                attributeName : value,
                orgid : $('#orgidselector').find("option:selected").val()
        };

        $.ajax({
            url: ctx+'orgattr/getAttributePage.json',
            dataType: "html",
            type: "POST",
            data: JSON.stringify(data),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data, textStatus, jqXHR)
            {
                $('#maincontentbody').append(data);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert("getAttributePage error :"+jqXHR+":"+textStatus+":"+errorThrown);
                console.log( "getAttributePage error :"+jqXHR+":"+textStatus+":"+errorThrown);
            }
        });
    });

    //Bind callback functions with buttons
    $.each(buttonfunctioanlities, function(k, v) {
        formsubmitFunction=v.submitFunction;
        formsubmitFunctionArgs=v.submitFunctionArgs;
        submitbuttonid=v.submitbuttonid;
        if(formsubmitFunction != ''){
            if(formsubmitFunctionArgs.legth == 0){
                $("#"+submitbuttonid).off('click').on('click', window[formsubmitFunction]);
            }else{
                $("#"+submitbuttonid).off('click').on('click', formsubmitFunctionArgs, window[formsubmitFunction]);
            }
        }
    });
}

1 个答案:

答案 0 :(得分:0)

这可以通过将延迟请求放入数组

来实现
function loadHtml(methodargs){

    header=methodargs.header;
    htmlname=methodargs.htmlname;
    subsection=methodargs.subsection;
    callbackfunction=methodargs.callbackfunction;
    buttonfunctioanlities = methodargs.buttons;


    $("#mainContentSubmit").off('click');
    $('#maincontentbody').empty();

    $("#maincontentheader").html(header);
    var ajaxrequests = [];
    if(htmlname != ''){
        /*ajaxrequests.push($( "#maincontentbody" ).load( ctx+"/loadpage?pagename="+htmlname), function( response, status, xhr ) {
            console.log('response :'+response);
        });*/
        ajaxrequests.push(
            $.ajax({
                url: ctx+"/loadpage?pagename="+htmlname,
                cache: false,
                success: function(data, textStatus, jqXHR) {
                    //$( "#maincontentbody" ).html($(data));
                    return data;
                }
            })
        );
    }

    $.each(subsection,function(index,value){
        var data = {
                attributeName : value,
                orgid : $('#orgidselector').find("option:selected").val()
        };

        ajaxrequests.push(
            $.ajax({
                url: ctx+'orgattr/getAttributePage.json',
                dataType: "html",
                type: "POST",
                data: JSON.stringify(data),
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json");
                },
                success: function(data, textStatus, jqXHR)
                {
                    return data;

                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert("getAttributePage error :"+jqXHR+":"+textStatus+":"+errorThrown);
                    console.log( "getAttributePage error :"+jqXHR+":"+textStatus+":"+errorThrown);
                }
            })
      );
    });

    $.when.apply($, ajaxrequests).then(function( data ) {
        $.each(arguments, function (i, data) {
            console.log(data); //data is the value returned by each of the ajax requests

            $('#maincontentbody').append(data);
        });

        $.each(callbackfunction, function( index, value ) {
            window[value]();
        });
    }).then(function( data ) {
        //Move to different block
        $.each(buttonfunctioanlities, function(k, v) {
            formsubmitFunction=v.submitFunction;
            formsubmitFunctionArgs=v.submitFunctionArgs;
            submitbuttonid=v.submitbuttonid;
            if($("#"+submitbuttonid).length){
                if(formsubmitFunction != ''){
                    if(formsubmitFunctionArgs.length == 0){
                        $("#"+submitbuttonid).off('click').on('click', window[formsubmitFunction]);
                    }else{
                        $("#"+submitbuttonid).off('click').on('click', formsubmitFunctionArgs, window[formsubmitFunction]);
                    }
                }
            }
        });
    });
}