Created
February 16, 2011 01:15
-
-
Save rkatic/828650 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery._Deferred = function() { | |
var // callbacks list | |
callbacks = [], | |
// stored [ context , args ] | |
fired, | |
// to avoid firing when already doing so (or it is halted) | |
firing, | |
// flag to know if the deferred has been cancelled | |
cancelled, | |
// the deferred itself | |
deferred = { | |
// done( f1, f2, ...) | |
done: function() { | |
if ( !cancelled ) { | |
var args = arguments, | |
i, | |
length, | |
elem, | |
type, | |
_fired; | |
if ( fired && !firing ) { | |
_fired = fired; | |
fired = 0; | |
} | |
for ( i = 0, length = args.length; i < length; i++ ) { | |
elem = args[ i ]; | |
type = jQuery.type( elem ); | |
if ( type === "array" ) { | |
deferred.done.apply( deferred, elem ); | |
} else if ( type === "function" ) { | |
callbacks.push( elem ); | |
} | |
} | |
if ( _fired ) { | |
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); | |
} | |
} | |
return this; | |
}, | |
// resolve with given context and args | |
resolveWith: function( context, args ) { | |
if ( !cancelled && !fired && !firing ) { | |
firing = 1; | |
fired = [ context, args ]; | |
while( callbacks[ 0 ] ) { | |
callbacks.shift().apply( context, args ); | |
} | |
firing = 0; | |
} | |
return this; | |
}, | |
// resolve with this as context and given arguments | |
resolve: function() { | |
deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments ); | |
return this; | |
}, | |
// Resume resolving (in case it is halted by an exception). | |
resume: function() { | |
firing = 0; | |
deferred.done(); | |
return this; | |
}, | |
// Has this deferred been resolved? | |
isResolved: function() { | |
return !!fired; | |
}, | |
// Cancel | |
cancel: function() { | |
cancelled = 1; | |
callbacks = []; | |
return this; | |
} | |
}; | |
return deferred; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment