Just a quick note on jQuery Deferred objects…

   1: var goGetSomeHtml = function() {
   2:     var deferred = $.Deferred();
   3:     $.ajax({
   4:         url: “some.htm”
   5:     }).done(function(data) {
   6:         deferred.resolve(data);
   7:     }).fail(function(jqXHR, textStatus) {
   8:         deferred.reject({ xhr:jqXHR, textStatus: textStatus });
   9:     });
  10:     return deferred.promise();
  11: };

They’re basically a callback wrapper. This example is a bit redundant since jQuery $.ajax returns a Deferred already, but you get the idea. You can use this for anything that requires a callback. It provides a pattern that pushes the callback function into user code in a way that is standardized. The resolve and reject functions on deferred pass their parameters into the callbacks in the done/fail functions.

This lets you pass the deferred promise around (a promise is just a deferred with the resolve/reject removed from its interface). A bit cleaner functional approach that removes the need for you to worry about call/apply syntax and context.

The above can then be used like this:

   1: $.when(
   2:     goGetSomeHtml()
   3: ).done(function(data) {
   4:     //do success callback stuff here...
   5: }).fail(function(state) {
   6:     //use state.xhr or state.textStatus to handle the error somehow.
   7: }

Enjoy. Smile