Permalink
Browse files

Adds always and chain methods to deferreds.

  • Loading branch information...
1 parent 75a4bc4 commit bb99899ca0de93dd12f5a53f409ff6f72bfcf94c @jaubourg jaubourg committed Apr 7, 2011
Showing with 282 additions and 128 deletions.
  1. +30 −2 src/deferred.js
  2. +252 −126 test/unit/deferred.js
View
@@ -1,7 +1,7 @@
(function( jQuery ) {
var // Promise methods
- promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
+ promiseMethods = "done fail isResolved isRejected promise then always chain".split( " " ),
// Static reference to slice
sliceDeferred = [].slice;
@@ -100,10 +100,38 @@ jQuery.extend({
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
+ always: function() {
+ return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
+ },
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
+ // Chain
+ chain: function( fnDone, fnFail ) {
+ return jQuery.Deferred(function( newDefer ) {
+ jQuery.each( {
+ done: [ fnDone, "resolve" ],
+ fail: [ fnFail, "reject" ]
+ }, function( handler, data ) {
+ var fn = data[ 0 ],
+ action = data[ 1 ],
+ returned;
+ if ( jQuery.isFunction( fn ) ) {
+ deferred[ handler ](function() {
+ returned = fn.apply( this, arguments );
+ if ( jQuery.isFunction( returned.promise ) ) {
+ returned.promise().then( newDefer.resolve, newDefer.reject );
+ } else {
+ newDefer[ action ]( returned );
+ }
+ });
+ } else {
+ deferred[ handler ]( newDefer[ action ] );
+ }
+ } );
+ }).promise();
+ },
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
@@ -169,4 +197,4 @@ jQuery.extend({
}
});
-})( jQuery );
+})( jQuery );
Oops, something went wrong. Retry.

0 comments on commit bb99899

Please sign in to comment.