Refactors jQuery.when to avoid unnecessary recursion and limit function calls as much as possible.
This commit is contained in:
parent
cacea6f7e7
commit
3663836b01
42
src/core.js
42
src/core.js
|
@ -905,13 +905,13 @@ jQuery.extend({
|
||||||
}
|
}
|
||||||
var i = promiseMethods.length;
|
var i = promiseMethods.length;
|
||||||
while( i-- ) {
|
while( i-- ) {
|
||||||
obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
|
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
} );
|
} );
|
||||||
// Make sure only one callback list will be used
|
// Make sure only one callback list will be used
|
||||||
deferred.then( failDeferred.cancel, deferred.cancel );
|
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
|
||||||
// Unexpose cancel
|
// Unexpose cancel
|
||||||
delete deferred.cancel;
|
delete deferred.cancel;
|
||||||
// Call given func if any
|
// Call given func if any
|
||||||
|
@ -923,24 +923,34 @@ jQuery.extend({
|
||||||
|
|
||||||
// Deferred helper
|
// Deferred helper
|
||||||
when: function( object ) {
|
when: function( object ) {
|
||||||
var args = arguments,
|
var lastIndex = arguments.length,
|
||||||
length = args.length,
|
deferred = lastIndex <= 1 && object && jQuery.isFunction( object.promise ) ?
|
||||||
deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
|
|
||||||
object :
|
object :
|
||||||
jQuery.Deferred(),
|
jQuery.Deferred(),
|
||||||
promise = deferred.promise(),
|
promise = deferred.promise();
|
||||||
resolveArray;
|
|
||||||
|
|
||||||
if ( length > 1 ) {
|
if ( lastIndex > 1 ) {
|
||||||
resolveArray = new Array( length );
|
var array = slice.call( arguments, 0 ),
|
||||||
jQuery.each( args, function( index, element ) {
|
count = lastIndex,
|
||||||
jQuery.when( element ).then( function( value ) {
|
iCallback = function( index ) {
|
||||||
resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
|
return function( value ) {
|
||||||
if( ! --length ) {
|
array[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
|
||||||
deferred.resolveWith( promise, resolveArray );
|
if ( !( --count ) ) {
|
||||||
|
deferred.resolveWith( promise, array );
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
while( ( lastIndex-- ) ) {
|
||||||
|
object = array[ lastIndex ];
|
||||||
|
if ( object && jQuery.isFunction( object.promise ) ) {
|
||||||
|
object.promise().then( iCallback(lastIndex), deferred.reject );
|
||||||
|
} else {
|
||||||
|
--count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ( !count ) {
|
||||||
|
deferred.resolveWith( promise, array );
|
||||||
}
|
}
|
||||||
}, deferred.reject );
|
|
||||||
} );
|
|
||||||
} else if ( deferred !== object ) {
|
} else if ( deferred !== object ) {
|
||||||
deferred.resolve( object );
|
deferred.resolve( object );
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue