Skip to content Skip to sidebar Skip to footer

Jquery When Done On Dynamically Pulled Function Call

I have the following code: In site-code.js .... var ajaxContentFunc = $(origin).data('modal-content-handler'); $.when(window[ajaxContentFunc]()).done(function (resp) { kModal.

Solution 1:

As far as I can tell, you are 95% there.

Use .then() instead of .done() and return the promise returned by $.ajax().then() :

functionajaxContentGeneration() {
    return $.ajax({
        url: "tests/ajax/AjaxTest.aspx",
        data: { exampleType: "modal-ajax" },
        dataType: "html"
    }).then(function (data) {
        return $(data).find("#ajax-content"); // this will return jQuery// return $(data).find("#ajax-content").html(); // this will return html
    });
}

You can probably also purge $.when() from the top-level call :

var ajaxContentFunc = $(origin).data("modal-content-handler");
window[ajaxContentFunc]().then(function (resp) {
    // `resp` is whatever was returned by the `return $(data).find()...` statement above
    kModal.showContent(resp);
});

The reason I say "probably" is that $.when() would be necessary if value-returning (not promise-returning) functions could be called instead of ajaxContentGeneration().

Solution 2:

Another way would be to do:

// should really be renamed...functionajaxContentGeneration(){
    return $.ajax({
        url      : "tests/ajax/AjaxTest.aspx",
        data     : { exampleType: "modal-ajax" },
        dataType : "html"
    })
}

Somewhere else:

var ajaxContentFunc = $(origin).data("modal-content-handler");

window[ajaxContentFunc]()
    .done(function(RES){
        kModal.showContent( $(RES).find("#ajax-content") );
    });

So the functionality of the ajaxContentGeneration function will be to return an AJAX promise, and not have it manipulated inside it, but do the manipulation where needed (getting the #ajax-content element from the response)


Note that this whole thing is bad practice JS design, and you should avoid having functions on top of the window object, but instead on another object.

Post a Comment for "Jquery When Done On Dynamically Pulled Function Call"