elad.chen
elad.chen

Reputation: 2425

jQuery Deferred objects

I'm working on a 'one page application' and i'm looking for a way to make sure page rendering is finished.

My app flow is as such:

  1. Draw the navigation markup
  2. Add an overlay indicating page content is being fetched
  3. Actually load content & inject it to the page content area

Now this is where I fall short:

After the page content has been injected, I initialize markup dependent widgets (bootstrap, custom events, etc.).

What this means is, page content could still be manipulated, as such, I was wondering if I could use jQuery's deferred object (and how) as a functions queue, with functions that can be performing async operations as well as plain old synchronous functions.

Using that, I wish to be able to tell when all widgets have been initialized, and then remove the page loading indicator.

Upvotes: 0

Views: 51

Answers (1)

Gerson Goulart
Gerson Goulart

Reputation: 634

You could use jQuery's deferred object to create a queue of async functions.

Here is an example implementation (by jsfiddle/coffeeandcode):

var Queue = function() {
    var lastPromise = null;

    this.add = function(obj, method, args, context) {
        var methodDeferred = $.Deferred();
        var queueDeferred = this.setup();
        if(context === undefined) { context = obj; }

        // execute next queue method
        queueDeferred.done(function() {


            // call actual method and wrap output in deferred
            setTimeout(function() {
                obj[method].apply(context, args);
                methodDeferred.resolve();
            }, 100);


        });
        lastPromise = methodDeferred.promise();
    };

    this.setup = function() {
        var queueDeferred = $.Deferred();

        // when the previous method returns, resolve this one
        $.when(lastPromise).always(function() {
            queueDeferred.resolve();
        });

        return queueDeferred.promise();
    }
};

You can see the code in action here:

http://jsfiddle.net/coffeeandcode/yg9P6/

Upvotes: 1

Related Questions