Monday, January 17, 2011

JQuery 1.5 promises a better future.

One of the new features of the unreleased JQuery 1.5 is a new $.ajax module.

Apart from many bug fixes, the most interesting, and useful part for me is that it now uses promises. Those familiar with python and twisted, or the JavaScript library mockikit, Dojo Deferred, or java.util.concurrent.Future might know these as deferreds or futures. jQuery is using promises, and not futures. They are similar but slightly different. It's a very commonly used technique in concurrency libraries now - so it is good that jQuery has hopped on board.

Since jQuery always returns a promise, you can now add callbacks even after you have done the call... or even change the callback later.
jQuery.getJSON( url ).error( errorCallback )

Pluggable ajax lets us test more easily

The other great thing(from a testing perspective) is that jQuery now allows you to use plug in mock implementations. This lets you make a fake ajax implementation for your unit tests more easily.

This pluggable architecture could also lead to people making other plugins that act the same as the ajax interface. Which could come in handy if you had a strange requirement, or you want to develop an alternative communication method - and be able to reuse much of the jQuery code.

Subclassing jQuery object

Another new area where jQuery helps extensibility, is the ability to subclass the jQuery object, and override methods - without it breaking the public interface to jQuery.

This is useful if you want to make a plugin that changes a few parts of jQuery for it's own uses, and not be worried that it will break 17 other plugins.

(function(globaljQuery, $) {
// private functions
$.fn.privateFunction = function(){ };

// overwrite an existing function without breaking other plugins
// which use the global jQuery function.
$.fn.popularExistingFunction = function(){ };

// Expose some public functions
globaljQuery.fn.myPublicFunction = function(){ };

})(jQuery, jQuery.subClass());

You can try the jQuery 1.5 beta 1 yourself if you want to have a play. I'm sure they will appreciate any bug reports.

No comments: