12 June 2012

jQuery Deferred for Asynchronous callbacks

jQuery Deferred is a convenient way to perform Asynchronous callbacks.
For example, during the load of a page if you are performing a javaScript operation that takes some time to execute, an asynchronous callback can be used. The page will load without blocking.

jQuery has the $.Deferred() feature that can register multiple callbacks and invoke them.
The deferred.done() adds an handler to be called when the Deferred object is resolved (doneCallbacks).
The deferred.resolve() resolves a Deferred object and calls any doneCallbacks with the given args.

The following code is an example usage:
var deferred = new $.Deferred();

deferred.done(function(message) { 
    // Put the code to execute asynchronously here

deferred.resolve('"hello world!!!"');
There is a lot more about the Deferred Object in the jQuery documentation.

No comments: