1
\$\begingroup\$

I've created a class that allows me to load resources, execute a callback after each individual request has been made and finally, a final callback that can assume all said resources are available.

This is something I came up with when developing something in ExtJS, so there were no formal promises (done, success, then, always, etc.) like you have in jQuery.

Here's the class:

function ResourceLoader(finalCallback) {

    this.requests = [];
    this.finalCallback = finalCallback;

    //pops an additional request on the queue...
    this.addRequest = function (request) {
        this.requests.push(request);
    }

    //execute them all...
    this.executeRequests = function () {

        for (var i = 0; i <= this.requests.length - 1; i++) {

            //if 'errorCallback' member was specified, we will execute it, otherwise, create a empty function.
            var ec = (this.requests[i].errorCallback) ? this.requests[i].errorCallback : function () { };

            //if we are executing not the last request...
            if (i < this.requests.length - 1) {
                $.ajax(this.requests[i])
                .done(this.requests[i].callback)
                .error(ec);
            }
            else {
                //when executing the last queued request, execute the final callback.
                $.when($.ajax(this.requests[i])
                .done(this.requests[i].callback)
                .error(ec)).then(this.finalCallback);
            }

        }
    }

}

This works as intended.

var loader = new ResourceLoader(function () {
    //the final callback hides the spinner...
    $body = $("body");
    $body.removeClass("loading");
});

loader.addRequest({
    method: 'get',
    url: '/HtmlParts/ChatRoom/MessageSelf.html',
    callback: function (data) {
        $messageMe = data;
    }
});

loader.addRequest({
    method: 'get',
    url: '/HtmlParts/ChatRoom/MessageOthers.html',
    callback: function (data) {
        $messageOthers = data;
    }
});

loader.executeRequests();

Here I'm using it to load static HTML content from separate physical file that I can use as I wish to dynamically add instances of them on the fly later on.

Is there a better way to do this in jQuery ?

Thanks.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.