From 114846d38dc05afec18158e2365d6a449851819b Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 6 May 2011 18:35:08 +0200 Subject: [PATCH 01/66] Replaces jQuery._Deferred with the much more flexible (and public) jQuery.Callbacks. Hopefully, jQuery.Callbacks can be used as a base for all callback lists needs in jQuery. Also adds progress callbacks to Deferreds (handled in jQuery.when too). Needs more unit tests. --- Makefile | 1 + src/ajax.js | 6 +- src/callbacks.js | 206 +++++++++++++++++++++++++++++ src/core.js | 8 +- src/deferred.js | 229 ++++++++++++--------------------- src/queue.js | 16 +-- test/data/offset/absolute.html | 2 +- test/data/offset/body.html | 2 +- test/data/offset/fixed.html | 2 +- test/data/offset/relative.html | 2 +- test/data/offset/scroll.html | 2 +- test/data/offset/static.html | 2 +- test/data/offset/table.html | 2 +- test/index.html | 2 + test/unit/deferred.js | 106 --------------- 15 files changed, 316 insertions(+), 272 deletions(-) create mode 100644 src/callbacks.js diff --git a/Makefile b/Makefile index 06cee5de..3bb56e3d 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,7 @@ COMPILER = ${JS_ENGINE} ${BUILD_DIR}/uglify.js --unsafe POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ + ${SRC_DIR}/callbacks.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/ajax.js b/src/ajax.js index a16717b0..b9be5eb1 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -382,7 +382,7 @@ jQuery.extend({ jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), - completeDeferred = jQuery._Deferred(), + completeCallbacks = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key @@ -560,7 +560,7 @@ jQuery.extend({ } // Complete - completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); + completeCallbacks.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); @@ -575,7 +575,7 @@ jQuery.extend({ deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; - jqXHR.complete = completeDeferred.done; + jqXHR.complete = completeCallbacks.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { diff --git a/src/callbacks.js b/src/callbacks.js new file mode 100644 index 00000000..5d5eb98e --- /dev/null +++ b/src/callbacks.js @@ -0,0 +1,206 @@ +(function( jQuery ) { + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * filter: an optional function that will be applied to each added callbacks, + * what filter returns will then be added provided it is not falsy. + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * relocate: like "unique" but will relocate the callback at the end of the list + * + */ +jQuery.Callbacks = function( flags, filter ) { + + // flags are optional + if ( typeof flags !== "string" ) { + filter = flags; + flags = undefined; + } + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !flags.once && [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // Add a list of callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // If we have to relocate, we remove the callback + // if it already exists + if ( flags.relocate ) { + object.remove( elem ); + } + // Unless we have a list with unicity and the + // function is already there, add it + if ( !( flags.unique && object.has( elem ) ) ) { + // Get the filtered function if needs be + actual = filter ? filter(elem) : elem; + if ( actual ) { + list.push( [ elem, actual ] ); + } + } + } + } + }, + object = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + add( arguments ); + // If we're not firing and we should call right away + if ( !firing && flags.memory && memory ) { + // Trick the list into thinking it needs to be fired + var tmp = memory; + memory = undefined; + object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + list.splice( i, 1 ); + i--; + // If we have some unicity property then + // we only need to do this once + if ( flags.unique || flags.relocate ) { + break; + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + object.disable(); + } + return this; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + var i; + if ( list && ( flags.once ? !memory && !firing : stack ) ) { + if ( firing ) { + stack.push( [ context, args ] ); + } else { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + try { + for ( i = 0; list && i < list.length; i++ ) { + if ( list[ i ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + break; + } + } + } finally { + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( i >= list.length && stack.length ) { + object.fire.apply( this, stack.shift() ); + } + } else if ( !flags.memory ) { + object.destroy(); + } else { + list = []; + } + } + } + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + object.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return object; +}; + +})( jQuery ); diff --git a/src/core.js b/src/core.js index 056fb88f..dc5f62cc 100644 --- a/src/core.js +++ b/src/core.js @@ -50,7 +50,7 @@ var jQuery = function( selector, context ) { // For matching the engine and version of the browser browserMatch, - // The deferred used on DOM ready + // The callback list used on DOM ready readyList, // The ready event handler @@ -249,7 +249,7 @@ jQuery.fn = jQuery.prototype = { jQuery.bindReady(); // Add the callback - readyList.done( fn ); + readyList.add( fn ); return this; }, @@ -404,7 +404,7 @@ jQuery.extend({ } // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); + readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { @@ -418,7 +418,7 @@ jQuery.extend({ return; } - readyList = jQuery._Deferred(); + readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. diff --git a/src/deferred.js b/src/deferred.js index 02f92b26..fb12866f 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -1,169 +1,105 @@ (function( jQuery ) { var // Promise methods - promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), + promiseMethods = "done fail progress isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - 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 ) { - _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 ); + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + promise, + deferred = { + // Copy existing methods from lists + done: doneList.add, + removeDone: doneList.remove, + fail: failList.add, + removeFail: failList.remove, + progress: progressList.add, + removeProgress: progressList.remove, + resolve: doneList.fire, + resolveWith: doneList.fireWith, + reject: failList.fire, + rejectWith: failList.fireWith, + ping: progressList.fire, + pingWith: progressList.pingWith, + isResolved: doneList.fired, + isRejected: failList.fired, + + // Create Deferred-specific methods + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "ping" ] + }, 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, newDefer.ping ); + } 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 ) { + if ( obj == null ) { + if ( promise ) { + return promise; } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } + promise = obj = {}; } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - // make sure args are available (#8421) - args = args || []; - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - finally { - fired = [ context, args ]; - firing = 0; - } + var i = promiseMethods.length; + while( i-- ) { + obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; + return obj; } }; - return deferred; - }, + // Handle lists exclusiveness + deferred.done( failList.disable, progressList.lock ) + .fail( doneList.disable, progressList.lock ); - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - 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, - pipe: 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 ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - }); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } + + // All done! return deferred; }, // Deferred helper when: function( firstParam ) { - var args = arguments, + var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, + pValues = new Array( length ), count = length, + pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); @@ -171,17 +107,22 @@ jQuery.extend({ return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { - // Strange bug in FF4: - // Values changed onto the arguments object sometimes end up as undefined values - // outside the $.when method. Cloning the object into a fresh array solves the issue - deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.pingWith( deferred, pValue ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { - if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject ); + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } diff --git a/src/queue.js b/src/queue.js index 66383c19..145bfd6f 100644 --- a/src/queue.js +++ b/src/queue.js @@ -1,7 +1,7 @@ (function( jQuery ) { -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", +function handleCBList( elem, type, src ) { + var deferDataKey = type + "cblst", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); @@ -14,7 +14,7 @@ function handleQueueMarkDefer( elem, type, src ) { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); - defer.resolve(); + defer.fireWith(); } }, 0 ); } @@ -43,7 +43,7 @@ jQuery.extend({ jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); + handleCBList( elem, type, "mark" ); } } }, @@ -90,7 +90,7 @@ jQuery.extend({ if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); - handleQueueMarkDefer( elem, type, "queue" ); + handleCBList( elem, type, "queue" ); } } }); @@ -146,7 +146,7 @@ jQuery.fn.extend({ elements = this, i = elements.length, count = 1, - deferDataKey = type + "defer", + deferDataKey = type + "cblst", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; @@ -159,9 +159,9 @@ jQuery.fn.extend({ if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; - tmp.done( resolve ); + tmp.add( resolve ); } } resolve(); diff --git a/test/data/offset/absolute.html b/test/data/offset/absolute.html index 9d7990a3..2002a535 100644 --- a/test/data/offset/absolute.html +++ b/test/data/offset/absolute.html @@ -16,7 +16,7 @@ #positionTest { position: absolute; } - + diff --git a/test/data/offset/body.html b/test/data/offset/body.html index 8dbf282d..a661637f 100644 --- a/test/data/offset/body.html +++ b/test/data/offset/body.html @@ -9,7 +9,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/fixed.html b/test/data/offset/fixed.html index 81ba4ca7..c6eb9277 100644 --- a/test/data/offset/fixed.html +++ b/test/data/offset/fixed.html @@ -13,7 +13,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/relative.html b/test/data/offset/relative.html index 280a2fc0..6386eebd 100644 --- a/test/data/offset/relative.html +++ b/test/data/offset/relative.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/scroll.html b/test/data/offset/scroll.html index a0d1f4d1..0890d0ad 100644 --- a/test/data/offset/scroll.html +++ b/test/data/offset/scroll.html @@ -14,7 +14,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/static.html b/test/data/offset/static.html index a61b6d10..687e93e8 100644 --- a/test/data/offset/static.html +++ b/test/data/offset/static.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/table.html b/test/data/offset/table.html index 11fb0e79..06774325 100644 --- a/test/data/offset/table.html +++ b/test/data/offset/table.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/index.html b/test/index.html index 3d421a56..bf5b161a 100644 --- a/test/index.html +++ b/test/index.html @@ -9,6 +9,7 @@ + @@ -34,6 +35,7 @@ + diff --git a/test/unit/deferred.js b/test/unit/deferred.js index c71fbdbe..765dfd66 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -1,111 +1,5 @@ module("deferred", { teardown: moduleTeardown }); -jQuery.each( [ "", " - new operator" ], function( _, withNew ) { - - function createDeferred() { - return withNew ? new jQuery._Deferred() : jQuery._Deferred(); - } - - test("jQuery._Deferred" + withNew, function() { - - expect( 11 ); - - var deferred, - object, - test; - - deferred = createDeferred(); - - test = false; - - deferred.done( function( value ) { - equals( value , "value" , "Test pre-resolve callback" ); - test = true; - } ); - - deferred.resolve( "value" ); - - ok( test , "Test pre-resolve callbacks called right away" ); - - test = false; - - deferred.done( function( value ) { - equals( value , "value" , "Test post-resolve callback" ); - test = true; - } ); - - ok( test , "Test post-resolve callbacks called right away" ); - - deferred.cancel(); - - test = true; - - deferred.done( function() { - ok( false , "Cancel was ignored" ); - test = false; - } ); - - ok( test , "Test cancel" ); - - deferred = createDeferred().resolve(); - - try { - deferred.done( function() { - throw "Error"; - } , function() { - ok( true , "Test deferred do not cancel on exception" ); - } ); - } catch( e ) { - strictEqual( e , "Error" , "Test deferred propagates exceptions"); - deferred.done(); - } - - test = ""; - deferred = createDeferred().done( function() { - - test += "A"; - - }, function() { - - test += "B"; - - } ).resolve(); - - strictEqual( test , "AB" , "Test multiple done parameters" ); - - test = ""; - - deferred.done( function() { - - deferred.done( function() { - - test += "C"; - - } ); - - test += "A"; - - }, function() { - - test += "B"; - } ); - - strictEqual( test , "ABC" , "Test done callbacks order" ); - - deferred = createDeferred(); - - deferred.resolveWith( jQuery , [ document ] ).done( function( doc ) { - ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" ); - }); - - // #8421 - deferred = createDeferred(); - deferred.resolveWith().done(function() { - ok( true, "Test resolveWith can be called with no argument" ); - }); - }); -} ); - jQuery.each( [ "", " - new operator" ], function( _, withNew ) { function createDeferred( fn ) { From e79fdebcee78096c5bb51e9b9d2841d548f22066 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 00:23:00 +0200 Subject: [PATCH 02/66] Added stopOnFalse method description in comments and reformatted then in the process. --- src/callbacks.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index 5d5eb98e..ab700887 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -28,15 +28,17 @@ function createFlags( flags ) { * * Possible flags: * - * once: will ensure the callback list can only be fired once (like a Deferred) + * once: will ensure the callback list can only be fired once (like a Deferred) * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) * - * unique: will ensure a callback can only be added once (no duplicate in the list) + * unique: will ensure a callback can only be added once (no duplicate in the list) * - * relocate: like "unique" but will relocate the callback at the end of the list + * relocate: like "unique" but will relocate the callback at the end of the list + * + * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags, filter ) { From 593fee1841fe5c9592c98167a6917d61e113357e Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 03:38:54 +0200 Subject: [PATCH 03/66] First bunch of unit tests for jQuery.Callbacks. --- test/unit/callbacks.js | 180 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 test/unit/callbacks.js diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js new file mode 100644 index 00000000..2f45337e --- /dev/null +++ b/test/unit/callbacks.js @@ -0,0 +1,180 @@ +module("callbacks", { teardown: moduleTeardown }); + +(function() { + +var output, + addToOutput = function( string ) { + return function() { + output += string; + }; + }, + outputA = addToOutput( "A" ), + outputB = addToOutput( "B" ), + outputC = addToOutput( "C" ), + tests = { + "": "X XABCABCC X XBB X", + "once": "X X X X X", + "memory": "XABC XABCABCCC XA XBB XB", + "unique": "X XABCA X XBB X", + "relocate": "X XAABC X XBB X", + "stopOnFalse": "X XABCABCC X XBB X", + "once memory": "XABC X XA X XA", + "once unique": "X X X X X", + "once relocate": "X X X X X", + "once stopOnFalse": "X X X X X", + "memory unique": "XA XABCA XA XBB XB", + "memory relocate": "XB XAABC XA XBB XB", + "memory stopOnFalse": "XABC XABCABCCC XA XBB XB", + "unique relocate": "X XAABC X XBB X", + "unique stopOnFalse": "X XABCA X XBB X", + "relocate stopOnFalse": "X XAABC X XBB X" + }, + filters = { + "no filter": undefined, + "filter": function( fn ) { + return function() { + return fn.apply( this, arguments ); + }; + } + }; + +jQuery.each( tests, function( flags, resultString ) { + + function createList() { + return jQuery.Callbacks( flags ); + } + + jQuery.each( filters, function( filterLabel, filter ) { + + test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { + + expect( 17 ); + + // Give qunit a little breathing room + stop(); + setTimeout( start, 0 ); + + var cblist; + results = resultString.split( /\s+/ ); + + // Basic binding and firing + output = "X"; + cblist = createList(); + cblist.add(function( str ) { + output += str; + }); + cblist.fire( "A" ); + strictEqual( output, "XA", "Basic binding and firing" ); + output = "X"; + cblist.disable(); + cblist.add(function( str ) { + output += str; + }); + strictEqual( output, "X", "Adding a callback after disabling" ); + cblist.fire( "A" ); + strictEqual( output, "X", "Firing after disabling" ); + + // Basic binding and firing (context, arguments) + output = "X"; + cblist = createList(); + cblist.add(function() { + equals( this, window, "Basic binding and firing (context)" ); + output += Array.prototype.join.call( arguments, "" ); + }); + cblist.fireWith( window, [ "A", "B" ] ); + strictEqual( output, "XAB", "Basic binding and firing (arguments)" ); + + // fireWith with no arguments + output = ""; + cblist = createList(); + cblist.add(function() { + equals( this, window, "fireWith with no arguments (context is window)" ); + strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" ); + }); + cblist.fireWith(); + + // Basic binding, removing and firing + output = "X"; + cblist = createList(); + cblist.add( outputA ); + cblist.add( outputB ); + cblist.add( outputC ); + cblist.remove( outputB ); + cblist.fire(); + strictEqual( output, "XAC", "Basic binding, removing and firing" ); + + // Empty + output = "X"; + cblist = createList(); + cblist.add( outputA ); + cblist.add( outputB ); + cblist.add( outputC ); + cblist.empty(); + cblist.fire(); + strictEqual( output, "X", "Empty" ); + + // Locking + output = "X"; + cblist = createList(); + cblist.add( function( str ) { + output += str; + }); + cblist.lock(); + cblist.add( function( str ) { + output += str; + }); + cblist.fire( "A" ); + cblist.add( function( str ) { + output += str; + }); + strictEqual( output, "X", "Lock early" ); + + // Ordering + output = "X"; + cblist = createList(); + cblist.add( function() { + cblist.add( outputC ); + outputA(); + }, outputB ); + cblist.fire(); + strictEqual( output, "XABC", "Proper ordering" ); + + // Add and fire again + output = "X"; + cblist.add( function() { + cblist.add( outputC ); + outputA(); + }, outputB ); + strictEqual( output, results.shift(), "Add after fire" ); + + output = "X"; + cblist.fire(); + strictEqual( output, results.shift(), "Fire again" ); + + // Multiple fire + output = "X"; + cblist = createList(); + cblist.add( function( str ) { + output += str; + } ); + cblist.fire( "A" ); + strictEqual( output, "XA", "Multiple fire (first fire)" ); + output = "X"; + cblist.add( function( str ) { + output += str; + } ); + strictEqual( output, results.shift(), "Multiple fire (first new callback)" ); + output = "X"; + cblist.fire( "B" ); + strictEqual( output, results.shift(), "Multiple fire (second fire)" ); + output = "X"; + cblist.add( function( str ) { + output += str; + } ); + strictEqual( output, results.shift(), "Multiple fire (second new callback)" ); + + }); + }); +}); + +})(); From 13734b729f2dd1130a6ac812b57338837987be48 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 03:39:41 +0200 Subject: [PATCH 04/66] Fixes for bugs found thanks to unit tests. --- src/callbacks.js | 62 ++++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index ab700887..62e27d2b 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -56,11 +56,13 @@ jQuery.Callbacks = function( flags, filter ) { var // Actual callback list list = [], // Stack of fire calls for repeatable lists - stack = !flags.once && [], + stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, + // Index of cells to remove in the list after firing + deleteAfterFire, // Add a list of callbacks to the list add = function( args ) { var i, @@ -79,15 +81,13 @@ jQuery.Callbacks = function( flags, filter ) { // if it already exists if ( flags.relocate ) { object.remove( elem ); + } else if ( flags.unique && object.has( elem ) ) { + continue; } - // Unless we have a list with unicity and the - // function is already there, add it - if ( !( flags.unique && object.has( elem ) ) ) { - // Get the filtered function if needs be - actual = filter ? filter(elem) : elem; - if ( actual ) { - list.push( [ elem, actual ] ); - } + // Get the filtered function if needs be + actual = filter ? filter( elem ) : elem; + if ( actual ) { + list.push( [ elem, actual ] ); } } } @@ -96,13 +96,15 @@ jQuery.Callbacks = function( flags, filter ) { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { + var length = list.length; add( arguments ); - // If we're not firing and we should call right away + // With memory, if we're not firing then + // we should call right away if ( !firing && flags.memory && memory ) { // Trick the list into thinking it needs to be fired var tmp = memory; memory = undefined; - object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + object.fireWith( tmp[ 0 ], tmp[ 1 ], length ); } } return this; @@ -113,9 +115,14 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { - list.splice( i, 1 ); - i--; + if ( list[ i ] && fn === list[ i ][ 0 ] ) { + if ( firing ) { + list[ i ] = undefined; + deleteAfterFire.push( i ); + } else { + list.splice( i, 1 ); + i--; + } // If we have some unicity property then // we only need to do this once if ( flags.unique || flags.relocate ) { @@ -132,7 +139,7 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { + if ( list[ i ] && fn === list[ i ][ 0 ] ) { return true; } } @@ -158,30 +165,39 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - var i; - if ( list && ( flags.once ? !memory && !firing : stack ) ) { + fireWith: function( context, args, start /* internal */ ) { + var i, + done, + stoppedOnFalse; + if ( list && stack && ( !flags.once || !memory && !firing ) ) { if ( firing ) { stack.push( [ context, args ] ); } else { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; + deleteAfterFire = []; try { - for ( i = 0; list && i < list.length; i++ ) { - if ( list[ i ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + for ( i = start || 0; list && i < list.length; i++ ) { + if (( stoppedOnFalse = list[ i ] && + list[ i ][ 1 ].apply( context, args ) === false && + flags.stopOnFalse )) { break; } } } finally { firing = false; if ( list ) { + done = ( stoppedOnFalse || i >= list.length ); + for ( i = 0; i < deleteAfterFire.length; i++ ) { + list.splice( deleteAfterFire[ i ], 1 ); + } if ( !flags.once ) { - if ( i >= list.length && stack.length ) { - object.fire.apply( this, stack.shift() ); + if ( done && stack && stack.length ) { + object.fireWith.apply( this, stack.shift() ); } } else if ( !flags.memory ) { - object.destroy(); + object.disable(); } else { list = []; } From b3d176d2cfddb544d4920d940cd1858251de671c Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 16:11:00 +0200 Subject: [PATCH 05/66] Simplifies how removal when firing is handled. Removes exception handling (lets the list deadlock). Makes sure no external code can fire the list from a given index (only possible internally). --- src/callbacks.js | 72 ++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 42 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index 62e27d2b..e0a70fed 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -61,8 +61,10 @@ jQuery.Callbacks = function( flags, filter ) { memory, // Flag to know if list is currently firing firing, - // Index of cells to remove in the list after firing - deleteAfterFire, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Index of currently firing callback (modified by remove if needed) + firingIndex, // Add a list of callbacks to the list add = function( args ) { var i, @@ -101,10 +103,10 @@ jQuery.Callbacks = function( flags, filter ) { // With memory, if we're not firing then // we should call right away if ( !firing && flags.memory && memory ) { - // Trick the list into thinking it needs to be fired var tmp = memory; memory = undefined; - object.fireWith( tmp[ 0 ], tmp[ 1 ], length ); + firingStart = length; + object.fireWith( tmp[ 0 ], tmp[ 1 ] ); } } return this; @@ -112,17 +114,14 @@ jQuery.Callbacks = function( flags, filter ) { // Remove a callback from the list remove: function( fn ) { if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( list[ i ] && fn === list[ i ][ 0 ] ) { - if ( firing ) { - list[ i ] = undefined; - deleteAfterFire.push( i ); - } else { - list.splice( i, 1 ); - i--; + for ( var i = 0; i < list.length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + // Handle firingIndex + if ( firing && i <= firingIndex ) { + firingIndex--; } + // Remove the element + list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique || flags.relocate ) { @@ -139,7 +138,7 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( list[ i ] && fn === list[ i ][ 0 ] ) { + if ( fn === list[ i ][ 0 ] ) { return true; } } @@ -165,10 +164,9 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Call all callbacks with the given context and arguments - fireWith: function( context, args, start /* internal */ ) { - var i, - done, - stoppedOnFalse; + fireWith: function( context, args ) { + var start = firingStart; + firingStart = 0; if ( list && stack && ( !flags.once || !memory && !firing ) ) { if ( firing ) { stack.push( [ context, args ] ); @@ -176,31 +174,21 @@ jQuery.Callbacks = function( flags, filter ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; - deleteAfterFire = []; - try { - for ( i = start || 0; list && i < list.length; i++ ) { - if (( stoppedOnFalse = list[ i ] && - list[ i ][ 1 ].apply( context, args ) === false && - flags.stopOnFalse )) { - break; - } + for ( firingIndex = start || 0; list && firingIndex < list.length; firingIndex++ ) { + if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + break; } - } finally { - firing = false; - if ( list ) { - done = ( stoppedOnFalse || i >= list.length ); - for ( i = 0; i < deleteAfterFire.length; i++ ) { - list.splice( deleteAfterFire[ i ], 1 ); - } - if ( !flags.once ) { - if ( done && stack && stack.length ) { - object.fireWith.apply( this, stack.shift() ); - } - } else if ( !flags.memory ) { - object.disable(); - } else { - list = []; + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + object.fireWith.apply( this, stack.shift() ); } + } else if ( !flags.memory ) { + object.disable(); + } else { + list = []; } } } From f8d08561f1749f54d2d183d0b3794d5eb7d09a99 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 16:12:43 +0200 Subject: [PATCH 06/66] Removes definition of createList and use jQuery.Callbacks directly to make things a bit less obfuscated. --- test/unit/callbacks.js | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index 2f45337e..c47c4b13 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -40,10 +40,6 @@ var output, jQuery.each( tests, function( flags, resultString ) { - function createList() { - return jQuery.Callbacks( flags ); - } - jQuery.each( filters, function( filterLabel, filter ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { @@ -59,7 +55,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding and firing output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function( str ) { output += str; }); @@ -76,7 +72,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding and firing (context, arguments) output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function() { equals( this, window, "Basic binding and firing (context)" ); output += Array.prototype.join.call( arguments, "" ); @@ -86,7 +82,7 @@ jQuery.each( tests, function( flags, resultString ) { // fireWith with no arguments output = ""; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function() { equals( this, window, "fireWith with no arguments (context is window)" ); strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" ); @@ -95,7 +91,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding, removing and firing output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( outputA ); cblist.add( outputB ); cblist.add( outputC ); @@ -105,7 +101,7 @@ jQuery.each( tests, function( flags, resultString ) { // Empty output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( outputA ); cblist.add( outputB ); cblist.add( outputC ); @@ -115,7 +111,7 @@ jQuery.each( tests, function( flags, resultString ) { // Locking output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; }); @@ -131,7 +127,7 @@ jQuery.each( tests, function( flags, resultString ) { // Ordering output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function() { cblist.add( outputC ); outputA(); @@ -153,7 +149,7 @@ jQuery.each( tests, function( flags, resultString ) { // Multiple fire output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; } ); From f392f8fcbcdbf1e7233048b698ccf5e28942ca1f Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 18:38:00 +0200 Subject: [PATCH 07/66] Adds disabled and locked. Simplifies logic in fireWith. --- src/callbacks.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index e0a70fed..dc7e176f 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -83,6 +83,7 @@ jQuery.Callbacks = function( flags, filter ) { // if it already exists if ( flags.relocate ) { object.remove( elem ); + // Skip if we're in unique mode and callback is already in } else if ( flags.unique && object.has( elem ) ) { continue; } @@ -155,6 +156,10 @@ jQuery.Callbacks = function( flags, filter ) { list = stack = memory = undefined; return this; }, + // Is it disabled? + disabled: function() { + return !list; + }, // Lock the list in its current state lock: function() { stack = undefined; @@ -163,18 +168,24 @@ jQuery.Callbacks = function( flags, filter ) { } return this; }, + // Is it locked? + locked: function() { + return !stack; + }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { - var start = firingStart; - firingStart = 0; - if ( list && stack && ( !flags.once || !memory && !firing ) ) { + if ( list ) { if ( firing ) { - stack.push( [ context, args ] ); - } else { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { args = args || []; - memory = !flags.memory || [ context, args ]; + memory = [ context, args ]; firing = true; - for ( firingIndex = start || 0; list && firingIndex < list.length; firingIndex++ ) { + firingIndex = firingStart || 0; + firingStart = 0; + for ( ; list && firingIndex < list.length; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { break; } @@ -183,7 +194,8 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { - object.fireWith.apply( this, stack.shift() ); + memory = stack.shift(); + object.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( !flags.memory ) { object.disable(); From 38aea727ece1220388a917bd350f8f17246a80b4 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 20:02:34 +0200 Subject: [PATCH 08/66] Adds addAfterFire flag. Unit tests updated with addAfterFire cases and also for when a callback returns false. --- src/callbacks.js | 27 ++++++++++++++++++----- test/unit/callbacks.js | 49 ++++++++++++++++++++++++++---------------- 2 files changed, 53 insertions(+), 23 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index dc7e176f..f0c0ca38 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -40,6 +40,9 @@ function createFlags( flags ) { * * stopOnFalse: interrupt callings when a callback returns false * + * addAfterFire: if callbacks are added while firing, then they are not executed until after + * the next call to fire/fireWith + * */ jQuery.Callbacks = function( flags, filter ) { @@ -63,6 +66,8 @@ jQuery.Callbacks = function( flags, filter ) { firing, // First callback to fire (used internally by add and fireWith) firingStart, + // End of the loop when firing + firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add a list of callbacks to the list @@ -101,9 +106,15 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { var length = list.length; add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + if ( !flags.addAfterFire ) { + firingLength = list.length; + } // With memory, if we're not firing then // we should call right away - if ( !firing && flags.memory && memory ) { + } else if ( flags.memory && memory ) { var tmp = memory; memory = undefined; firingStart = length; @@ -117,9 +128,14 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { for ( var i = 0; i < list.length; i++ ) { if ( fn === list[ i ][ 0 ] ) { - // Handle firingIndex - if ( firing && i <= firingIndex ) { - firingIndex--; + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } } // Remove the element list.splice( i--, 1 ); @@ -185,7 +201,8 @@ jQuery.Callbacks = function( flags, filter ) { firing = true; firingIndex = firingStart || 0; firingStart = 0; - for ( ; list && firingIndex < list.length; firingIndex++ ) { + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { break; } diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index c47c4b13..860a7cbb 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -12,22 +12,28 @@ var output, outputB = addToOutput( "B" ), outputC = addToOutput( "C" ), tests = { - "": "X XABCABCC X XBB X", - "once": "X X X X X", - "memory": "XABC XABCABCCC XA XBB XB", - "unique": "X XABCA X XBB X", - "relocate": "X XAABC X XBB X", - "stopOnFalse": "X XABCABCC X XBB X", - "once memory": "XABC X XA X XA", - "once unique": "X X X X X", - "once relocate": "X X X X X", - "once stopOnFalse": "X X X X X", - "memory unique": "XA XABCA XA XBB XB", - "memory relocate": "XB XAABC XA XBB XB", - "memory stopOnFalse": "XABC XABCABCCC XA XBB XB", - "unique relocate": "X XAABC X XBB X", - "unique stopOnFalse": "X XABCA X XBB X", - "relocate stopOnFalse": "X XAABC X XBB X" + "": "XABC X XABCABCC X XBB X XABA", + "once": "XABC X X X X X XABA", + "memory": "XABC XABC XABCABCCC XA XBB XB XABA", + "unique": "XABC X XABCA X XBB X XAB", + "relocate": "XABC X XAABC X XBB X XBA", + "stopOnFalse": "XABC X XABCABCC X XBB X XA", + "addAfterFire": "XAB X XABCAB X XBB X XABA", + "once memory": "XABC XABC X XA X XA XABA", + "once unique": "XABC X X X X X XAB", + "once relocate": "XABC X X X X X XBA", + "once stopOnFalse": "XABC X X X X X XA", + "once addAfterFire": "XAB X X X X X XABA", + "memory unique": "XABC XA XABCA XA XBB XB XAB", + "memory relocate": "XABC XB XAABC XA XBB XB XBA", + "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA", + "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA", + "unique relocate": "XABC X XAABC X XBB X XBA", + "unique stopOnFalse": "XABC X XABCA X XBB X XA", + "unique addAfterFire": "XAB X XABCA X XBB X XAB", + "relocate stopOnFalse": "XABC X XAABC X XBB X X", + "relocate addAfterFire": "XAB X XAA X XBB X XBA", + "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA" }, filters = { "no filter": undefined, @@ -44,7 +50,7 @@ jQuery.each( tests, function( flags, resultString ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { - expect( 17 ); + expect( 18 ); // Give qunit a little breathing room stop(); @@ -133,7 +139,7 @@ jQuery.each( tests, function( flags, resultString ) { outputA(); }, outputB ); cblist.fire(); - strictEqual( output, "XABC", "Proper ordering" ); + strictEqual( output, results.shift(), "Proper ordering" ); // Add and fire again output = "X"; @@ -169,6 +175,13 @@ jQuery.each( tests, function( flags, resultString ) { } ); strictEqual( output, results.shift(), "Multiple fire (second new callback)" ); + // Return false + output = "X"; + cblist = jQuery.Callbacks( flags ); + cblist.add( outputA, function() { return false; }, outputB ); + cblist.add( outputA ); + cblist.fire(); + strictEqual( output, results.shift(), "Callback returning false" ); }); }); }); From d54ae84f805e4d8057d3b7c9f28ea362553a4f01 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 00:40:45 +0200 Subject: [PATCH 09/66] Ensures a list with memory will not called further callbacks before the next fire/fireWith is in stopOnFalse mode and a callback returned false. Unit tests added. --- src/callbacks.js | 12 ++++++---- test/unit/callbacks.js | 52 +++++++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index f0c0ca38..0d126f80 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -113,8 +113,9 @@ jQuery.Callbacks = function( flags, filter ) { firingLength = list.length; } // With memory, if we're not firing then - // we should call right away - } else if ( flags.memory && memory ) { + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { var tmp = memory; memory = undefined; firingStart = length; @@ -179,7 +180,7 @@ jQuery.Callbacks = function( flags, filter ) { // Lock the list in its current state lock: function() { stack = undefined; - if ( !memory ) { + if ( !memory || memory === true ) { object.disable(); } return this; @@ -197,13 +198,14 @@ jQuery.Callbacks = function( flags, filter ) { } } else if ( !( flags.once && memory ) ) { args = args || []; - memory = [ context, args ]; + memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted break; } } @@ -214,7 +216,7 @@ jQuery.Callbacks = function( flags, filter ) { memory = stack.shift(); object.fireWith( memory[ 0 ], memory[ 1 ] ); } - } else if ( !flags.memory ) { + } else if ( memory === true ) { object.disable(); } else { list = []; diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index 860a7cbb..f179a6b1 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -12,28 +12,28 @@ var output, outputB = addToOutput( "B" ), outputC = addToOutput( "C" ), tests = { - "": "XABC X XABCABCC X XBB X XABA", - "once": "XABC X X X X X XABA", - "memory": "XABC XABC XABCABCCC XA XBB XB XABA", - "unique": "XABC X XABCA X XBB X XAB", - "relocate": "XABC X XAABC X XBB X XBA", - "stopOnFalse": "XABC X XABCABCC X XBB X XA", - "addAfterFire": "XAB X XABCAB X XBB X XABA", - "once memory": "XABC XABC X XA X XA XABA", - "once unique": "XABC X X X X X XAB", - "once relocate": "XABC X X X X X XBA", - "once stopOnFalse": "XABC X X X X X XA", - "once addAfterFire": "XAB X X X X X XABA", - "memory unique": "XABC XA XABCA XA XBB XB XAB", - "memory relocate": "XABC XB XAABC XA XBB XB XBA", - "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA", - "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA", - "unique relocate": "XABC X XAABC X XBB X XBA", - "unique stopOnFalse": "XABC X XABCA X XBB X XA", - "unique addAfterFire": "XAB X XABCA X XBB X XAB", - "relocate stopOnFalse": "XABC X XAABC X XBB X X", - "relocate addAfterFire": "XAB X XAA X XBB X XBA", - "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA" + "": "XABC X XABCABCC X XBB X XABA X", + "once": "XABC X X X X X XABA X", + "memory": "XABC XABC XABCABCCC XA XBB XB XABA XC", + "unique": "XABC X XABCA X XBB X XAB X", + "relocate": "XABC X XAABC X XBB X XBA X", + "stopOnFalse": "XABC X XABCABCC X XBB X XA X", + "addAfterFire": "XAB X XABCAB X XBB X XABA X", + "once memory": "XABC XABC X XA X XA XABA XC", + "once unique": "XABC X X X X X XAB X", + "once relocate": "XABC X X X X X XBA X", + "once stopOnFalse": "XABC X X X X X XA X", + "once addAfterFire": "XAB X X X X X XABA X", + "memory unique": "XABC XA XABCA XA XBB XB XAB XC", + "memory relocate": "XABC XB XAABC XA XBB XB XBA XC", + "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA X", + "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA XC", + "unique relocate": "XABC X XAABC X XBB X XBA X", + "unique stopOnFalse": "XABC X XABCA X XBB X XA X", + "unique addAfterFire": "XAB X XABCA X XBB X XAB X", + "relocate stopOnFalse": "XABC X XAABC X XBB X X X", + "relocate addAfterFire": "XAB X XAA X XBB X XBA X", + "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA X" }, filters = { "no filter": undefined, @@ -50,7 +50,7 @@ jQuery.each( tests, function( flags, resultString ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { - expect( 18 ); + expect( 19 ); // Give qunit a little breathing room stop(); @@ -182,6 +182,12 @@ jQuery.each( tests, function( flags, resultString ) { cblist.add( outputA ); cblist.fire(); strictEqual( output, results.shift(), "Callback returning false" ); + + // Add another callback (to control lists with memory do not fire anymore) + output = "X"; + cblist.add( outputC ); + strictEqual( output, results.shift(), "Adding a callback after one returned false" ); + }); }); }); From bf04081b6c45f8644fac8914a91c6f3395dd8ad3 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 00:53:09 +0200 Subject: [PATCH 10/66] Makes sure repeatable lists with memory are properly locked. --- src/callbacks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/callbacks.js b/src/callbacks.js index 0d126f80..bf86575e 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -191,7 +191,7 @@ jQuery.Callbacks = function( flags, filter ) { }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { - if ( list ) { + if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); From 5f9dff65871596dbf208ff90887466dd2fdf9c5e Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 01:31:29 +0200 Subject: [PATCH 11/66] Add Deferred.progress() unit tests and fixes some progress related typos and bugs. --- src/deferred.js | 13 +++-- test/unit/deferred.js | 110 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 106 insertions(+), 17 deletions(-) diff --git a/src/deferred.js b/src/deferred.js index fb12866f..7592e361 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -1,7 +1,7 @@ (function( jQuery ) { var // Promise methods - promiseMethods = "done fail progress isResolved isRejected promise then always pipe".split( " " ), + promiseMethods = "done removeDone fail removeFail progress removeProgress isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; @@ -25,7 +25,7 @@ jQuery.extend({ reject: failList.fire, rejectWith: failList.fireWith, ping: progressList.fire, - pingWith: progressList.pingWith, + pingWith: progressList.fireWith, isResolved: doneList.fired, isRejected: failList.fired, @@ -102,7 +102,8 @@ jQuery.extend({ pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : - jQuery.Deferred(); + jQuery.Deferred(), + promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; @@ -114,9 +115,7 @@ jQuery.extend({ function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.pingWith( deferred, pValue ); - } + deferred.pingWith( promise, pValues ); }; } if ( length > 1 ) { @@ -133,7 +132,7 @@ jQuery.extend({ } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } - return deferred.promise(); + return promise; } }); diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 765dfd66..f6f6fe0e 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -8,7 +8,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { test("jQuery.Deferred" + withNew, function() { - expect( 8 ); + expect( 14 ); createDeferred().resolve().then( function() { ok( true , "Success on resolve" ); @@ -34,6 +34,20 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { }).then( function( value ) { strictEqual( value , "done" , "Passed function executed" ); }); + + jQuery.each( "resolve reject".split( " " ), function( _, change ) { + createDeferred( function( defer ) { + var checked = 0; + defer.progress(function( value ) { + strictEqual( value, checked, "Progress: right value (" + value + ") received" ) + }); + for( checked = 0; checked < 3 ; checked++ ) { + defer.ping( checked ); + } + defer[ change ](); + defer.ping(); + }); + }); }); } ); @@ -101,6 +115,34 @@ test( "jQuery.Deferred.pipe - filtering (fail)", function() { } ); }); +test( "jQuery.Deferred.pipe - filtering (progress)", function() { + + expect(3); + + var defer = jQuery.Deferred(), + piped = defer.pipe( null, null, function( a, b ) { + return a * b; + } ), + value1, + value2, + value3; + + piped.progress(function( result ) { + value3 = result; + }); + + defer.progress(function( a, b ) { + value1 = a; + value2 = b; + }); + + defer.ping( 2, 3 ); + + strictEqual( value1, 2, "first reject value ok" ); + strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value3, 6, "result of filter ok" ); +}); + test( "jQuery.Deferred.pipe - deferred (done)", function() { expect(3); @@ -161,6 +203,36 @@ test( "jQuery.Deferred.pipe - deferred (fail)", function() { strictEqual( value3, 6, "result of filter ok" ); }); +test( "jQuery.Deferred.pipe - deferred (progress)", function() { + + expect(3); + + var defer = jQuery.Deferred(), + piped = defer.pipe( null, null, function( a, b ) { + return jQuery.Deferred(function( defer ) { + defer.resolve( a * b ); + }); + } ), + value1, + value2, + value3; + + piped.done(function( result ) { + value3 = result; + }); + + defer.progress(function( a, b ) { + value1 = a; + value2 = b; + }); + + defer.ping( 2, 3 ); + + strictEqual( value1, 2, "first reject value ok" ); + strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value3, 6, "result of filter ok" ); +}); + test( "jQuery.when" , function() { expect( 23 ); @@ -204,36 +276,54 @@ test( "jQuery.when" , function() { test("jQuery.when - joined", function() { - expect(25); + expect(50); var deferreds = { value: 1, success: jQuery.Deferred().resolve( 1 ), error: jQuery.Deferred().reject( 0 ), - futureSuccess: jQuery.Deferred(), - futureError: jQuery.Deferred() + futureSuccess: jQuery.Deferred().ping( true ), + futureError: jQuery.Deferred().ping( true ), + ping: jQuery.Deferred().ping( true ) }, willSucceed = { value: true, success: true, - error: false, + futureSuccess: true + }, + willError = { + error: true, + futureError: true + }, + willPing = { futureSuccess: true, - futureError: false + futureError: true, + ping: true }; jQuery.each( deferreds, function( id1, defer1 ) { jQuery.each( deferreds, function( id2, defer2 ) { var shouldResolve = willSucceed[ id1 ] && willSucceed[ id2 ], + shouldError = willError[ id1 ] || willError[ id2 ], + shouldPing = willPing[ id1 ] || willPing[ id2 ], expected = shouldResolve ? [ 1, 1 ] : [ 0, undefined ], - code = id1 + "/" + id2; - jQuery.when( defer1, defer2 ).done(function( a, b ) { + expectedPing = shouldPing && [ willPing[ id1 ], willPing[ id2 ] ], + code = id1 + "/" + id2; + + var promise = jQuery.when( defer1, defer2 ).done(function( a, b ) { if ( shouldResolve ) { same( [ a, b ], expected, code + " => resolve" ); + } else { + ok( false , code + " => resolve" ); } }).fail(function( a, b ) { - if ( !shouldResolve ) { - same( [ a, b ], expected, code + " => resolve" ); + if ( shouldError ) { + same( [ a, b ], expected, code + " => reject" ); + } else { + ok( false , code + " => reject" ); } + }).progress(function progress( a, b ) { + same( [ a, b ], expectedPing, code + " => progress" ); }); } ); } ); From 9edc3d4f398975b65ceeab4e35f11c314b51925e Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 01:03:30 +0200 Subject: [PATCH 12/66] Fixes repeatable callbacks list with memory disabling. Unit tests for Deferreds updated. --- src/callbacks.js | 57 ++++++++++++++++++++++--------------------- test/unit/deferred.js | 12 ++++----- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index bf86575e..b3635df7 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -100,6 +100,33 @@ jQuery.Callbacks = function( flags, filter ) { } } }, + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + object.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + object.disable(); + } else { + list = []; + } + } + }, object = { // Add a callback or a collection of callbacks to the list add: function() { @@ -116,10 +143,8 @@ jQuery.Callbacks = function( flags, filter ) { // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { - var tmp = memory; - memory = undefined; firingStart = length; - object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + fire( memory[ 0 ], memory[ 1 ] ); } } return this; @@ -197,31 +222,7 @@ jQuery.Callbacks = function( flags, filter ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - object.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - object.disable(); - } else { - list = []; - } - } + fire( context, args ); } } return this; diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 6e3cab89..ed568799 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -39,7 +39,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { createDeferred( function( defer ) { var checked = 0; defer.progress(function( value ) { - strictEqual( value, checked, "Progress: right value (" + value + ") received" ) + strictEqual( value, checked, "Progress: right value (" + value + ") received" ); }); for( checked = 0; checked < 3 ; checked++ ) { defer.ping( checked ); @@ -146,8 +146,8 @@ test( "jQuery.Deferred.pipe - filtering (progress)", function() { defer.ping( 2, 3 ); - strictEqual( value1, 2, "first reject value ok" ); - strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value1, 2, "first progress value ok" ); + strictEqual( value2, 3, "second progress value ok" ); strictEqual( value3, 6, "result of filter ok" ); }); @@ -236,8 +236,8 @@ test( "jQuery.Deferred.pipe - deferred (progress)", function() { defer.ping( 2, 3 ); - strictEqual( value1, 2, "first reject value ok" ); - strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value1, 2, "first progress value ok" ); + strictEqual( value2, 3, "second progress value ok" ); strictEqual( value3, 6, "result of filter ok" ); }); @@ -284,7 +284,7 @@ test( "jQuery.when" , function() { test("jQuery.when - joined", function() { - expect(50); + expect(53); var deferreds = { value: 1, From 96b0089c9ce5c65f9d002966256d90e778345a2a Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 01:59:00 +0200 Subject: [PATCH 13/66] Adds publish/subscribe channels. Unit tests added. --- Makefile | 1 + src/channel.js | 34 +++++++++++++++++++++++++++ test/index.html | 2 ++ test/unit/channel.js | 56 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 src/channel.js create mode 100644 test/unit/channel.js diff --git a/Makefile b/Makefile index 3bb56e3d..a21a7f38 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ ${SRC_DIR}/callbacks.js\ + ${SRC_DIR}/channel.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/channel.js b/src/channel.js new file mode 100644 index 00000000..013b65f1 --- /dev/null +++ b/src/channel.js @@ -0,0 +1,34 @@ +(function( jQuery ) { + + var channels = {}, + channelMethods = { + publish: "fire", + subscribe: "add", + unsubscribe: "remove" + }; + + jQuery.Channel = function( name ) { + var callbacks, + method, + channel = name && channels[ name ]; + if ( !channel ) { + callbacks = jQuery.Callbacks(); + channel = {}; + for ( method in channelMethods ) { + channel[ method ] = callbacks[ channelMethods[ method ] ]; + } + if ( name ) { + channels[ name ] = channel; + } + } + return channel; + }; + + jQuery.each( channelMethods, function( method ) { + jQuery[ method ] = function( name ) { + var channel = jQuery.Channel( name ); + channel[ method ].apply( channel, Array.prototype.slice.call( arguments, 1 ) ); + }; + }); + +})( jQuery ); diff --git a/test/index.html b/test/index.html index c4d0acc6..6ddd3b5c 100644 --- a/test/index.html +++ b/test/index.html @@ -10,6 +10,7 @@ + @@ -37,6 +38,7 @@ + diff --git a/test/unit/channel.js b/test/unit/channel.js new file mode 100644 index 00000000..ca8fcbd3 --- /dev/null +++ b/test/unit/channel.js @@ -0,0 +1,56 @@ +module("channel", { teardown: moduleTeardown }); + +test( "jQuery.Channel - Anonymous Channel", function() { + + expect( 4 ); + + var channel = jQuery.Channel(), + count = 0; + + function firstCallback( value ) { + strictEqual( count, 1, "Callback called when needed" ); + strictEqual( value, "test", "Published value received" ); + } + + count++; + channel.subscribe( firstCallback ); + channel.publish( "test" ); + channel.unsubscribe( firstCallback ); + count++; + channel.subscribe(function( value ) { + strictEqual( count, 2, "Callback called when needed" ); + strictEqual( value, "test", "Published value received" ); + }); + channel.publish( "test" ); + +}); + +test( "jQuery.Channel - Named Channel", function() { + + expect( 2 ); + + function callback( value ) { + ok( true, "Callback called" ); + strictEqual( value, "test", "Proper value received" ); + } + + jQuery.Channel( "test" ).subscribe( callback ); + jQuery.Channel( "test" ).publish( "test" ); + jQuery.Channel( "test" ).unsubscribe( callback ); + jQuery.Channel( "test" ).publish( "test" ); +}); + +test( "jQuery.Channel - Helpers", function() { + + expect( 2 ); + + function callback( value ) { + ok( true, "Callback called" ); + strictEqual( value, "test", "Proper value received" ); + } + + jQuery.subscribe( "test", callback ); + jQuery.publish( "test" , "test" ); + jQuery.unsubscribe( "test", callback ); + jQuery.publish( "test" , "test" ); +}); From 8c39fc855ea27f068eb758cee8d789a0619761f8 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 17:27:05 +0200 Subject: [PATCH 14/66] Shortens slice expression in channel helpers as per rwaldron's suggestion. --- src/channel.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/channel.js b/src/channel.js index 013b65f1..66b2745a 100644 --- a/src/channel.js +++ b/src/channel.js @@ -5,7 +5,8 @@ publish: "fire", subscribe: "add", unsubscribe: "remove" - }; + }, + sliceChannel = [].slice; jQuery.Channel = function( name ) { var callbacks, @@ -27,7 +28,7 @@ jQuery.each( channelMethods, function( method ) { jQuery[ method ] = function( name ) { var channel = jQuery.Channel( name ); - channel[ method ].apply( channel, Array.prototype.slice.call( arguments, 1 ) ); + channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) ); }; }); From 4dce543ee6c298f489f035c910501335fd0adbd5 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:16:51 +0200 Subject: [PATCH 15/66] $.Callbacks.remove now accepts multiple parameters (Unit test amended). Changed the variable name of the main object from "object" to "self" as per rwaldron's suggestions. --- src/callbacks.js | 57 ++++++++++++++++++++++++------------------ test/unit/callbacks.js | 8 +++--- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index b3635df7..8be35094 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -70,7 +70,7 @@ jQuery.Callbacks = function( flags, filter ) { firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, - // Add a list of callbacks to the list + // Add one or several callbacks to the list add = function( args ) { var i, length, @@ -87,9 +87,9 @@ jQuery.Callbacks = function( flags, filter ) { // If we have to relocate, we remove the callback // if it already exists if ( flags.relocate ) { - object.remove( elem ); + self.remove( elem ); // Skip if we're in unique mode and callback is already in - } else if ( flags.unique && object.has( elem ) ) { + } else if ( flags.unique && self.has( elem ) ) { continue; } // Get the filtered function if needs be @@ -100,6 +100,7 @@ jQuery.Callbacks = function( flags, filter ) { } } }, + // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; @@ -118,16 +119,17 @@ jQuery.Callbacks = function( flags, filter ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); - object.fireWith( memory[ 0 ], memory[ 1 ] ); + self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { - object.disable(); + self.disable(); } else { list = []; } } }, - object = { + // Actual Callbacks object + self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { @@ -150,25 +152,30 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Remove a callback from the list - remove: function( fn ) { + remove: function() { if ( list ) { - for ( var i = 0; i < list.length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ][ 0 ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } } } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique || flags.relocate ) { - break; + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique || flags.relocate ) { + break; + } } } } @@ -206,7 +213,7 @@ jQuery.Callbacks = function( flags, filter ) { lock: function() { stack = undefined; if ( !memory || memory === true ) { - object.disable(); + self.disable(); } return this; }, @@ -229,7 +236,7 @@ jQuery.Callbacks = function( flags, filter ) { }, // Call all the callbacks with the given arguments fire: function() { - object.fireWith( this, arguments ); + self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once @@ -238,7 +245,7 @@ jQuery.Callbacks = function( flags, filter ) { } }; - return object; + return self; }; })( jQuery ); diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index f179a6b1..54817de4 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -98,12 +98,10 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding, removing and firing output = "X"; cblist = jQuery.Callbacks( flags ); - cblist.add( outputA ); - cblist.add( outputB ); - cblist.add( outputC ); - cblist.remove( outputB ); + cblist.add( outputA, outputB, outputC ); + cblist.remove( outputB, outputC ); cblist.fire(); - strictEqual( output, "XAC", "Basic binding, removing and firing" ); + strictEqual( output, "XA", "Basic binding, removing and firing" ); // Empty output = "X"; From 55df21612572a2353ba26707b27b3a6664530b57 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:18:08 +0200 Subject: [PATCH 16/66] jQuery.subscribe now returns a handle that can be passed to jQuery.unsubscribe to... well... unsubscribe. Unit test amended. --- src/channel.js | 38 ++++++++++++++++++++++++-------------- test/unit/channel.js | 14 +++++++++++++- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/channel.js b/src/channel.js index 66b2745a..052c3f8f 100644 --- a/src/channel.js +++ b/src/channel.js @@ -1,11 +1,6 @@ (function( jQuery ) { var channels = {}, - channelMethods = { - publish: "fire", - subscribe: "add", - unsubscribe: "remove" - }, sliceChannel = [].slice; jQuery.Channel = function( name ) { @@ -14,10 +9,11 @@ channel = name && channels[ name ]; if ( !channel ) { callbacks = jQuery.Callbacks(); - channel = {}; - for ( method in channelMethods ) { - channel[ method ] = callbacks[ channelMethods[ method ] ]; - } + channel = { + publish: callbacks.fire, + subscribe: callbacks.add, + unsubscribe: callbacks.remove + }; if ( name ) { channels[ name ] = channel; } @@ -25,11 +21,25 @@ return channel; }; - jQuery.each( channelMethods, function( method ) { - jQuery[ method ] = function( name ) { - var channel = jQuery.Channel( name ); - channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) ); - }; + jQuery.extend({ + subscribe: function( id ) { + var channel = jQuery.Channel( id ), + args = sliceChannel.call( arguments, 1 ); + channel.subscribe.apply( channel, args ); + return { + channel: channel, + args: args + }; + }, + unsubscribe: function( id ) { + var channel = id && id.channel || jQuery.Channel( id ); + channel.unsubscribe.apply( channel, id && id.args || + sliceChannel.call( arguments, 1 ) ); + }, + publish: function( id ) { + var channel = jQuery.Channel( id ); + channel.publish.apply( channel, sliceChannel.call( arguments, 1 ) ); + } }); })( jQuery ); diff --git a/test/unit/channel.js b/test/unit/channel.js index ca8fcbd3..b5e7a726 100644 --- a/test/unit/channel.js +++ b/test/unit/channel.js @@ -42,7 +42,7 @@ test( "jQuery.Channel - Named Channel", function() { test( "jQuery.Channel - Helpers", function() { - expect( 2 ); + expect( 4 ); function callback( value ) { ok( true, "Callback called" ); @@ -53,4 +53,16 @@ test( "jQuery.Channel - Helpers", function() { jQuery.publish( "test" , "test" ); jQuery.unsubscribe( "test", callback ); jQuery.publish( "test" , "test" ); + + + var test = true, + subscription = jQuery.subscribe( "test", function() { + ok( test, "first callback called" ); + }, function() { + ok( test, "second callback called" ); + }); + jQuery.publish( "test" ); + test = false; + jQuery.unsubscribe( subscription ); + jQuery.publish( "test" ); }); From 3e7c04ec94efe08112b256b2fe2c2a404fced92f Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:37:38 +0200 Subject: [PATCH 17/66] Renames $.Channel as $.Topic to be on par with usual terminology of existing pub/sub implementations. --- Makefile | 2 +- src/channel.js | 45 ------------------------------ src/topic.js | 45 ++++++++++++++++++++++++++++++ test/index.html | 4 +-- test/unit/{channel.js => topic.js} | 28 +++++++++---------- 5 files changed, 62 insertions(+), 62 deletions(-) delete mode 100644 src/channel.js create mode 100644 src/topic.js rename test/unit/{channel.js => topic.js} (63%) diff --git a/Makefile b/Makefile index a21a7f38..4a0a80ba 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ ${SRC_DIR}/callbacks.js\ - ${SRC_DIR}/channel.js\ + ${SRC_DIR}/topic.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/channel.js b/src/channel.js deleted file mode 100644 index 052c3f8f..00000000 --- a/src/channel.js +++ /dev/null @@ -1,45 +0,0 @@ -(function( jQuery ) { - - var channels = {}, - sliceChannel = [].slice; - - jQuery.Channel = function( name ) { - var callbacks, - method, - channel = name && channels[ name ]; - if ( !channel ) { - callbacks = jQuery.Callbacks(); - channel = { - publish: callbacks.fire, - subscribe: callbacks.add, - unsubscribe: callbacks.remove - }; - if ( name ) { - channels[ name ] = channel; - } - } - return channel; - }; - - jQuery.extend({ - subscribe: function( id ) { - var channel = jQuery.Channel( id ), - args = sliceChannel.call( arguments, 1 ); - channel.subscribe.apply( channel, args ); - return { - channel: channel, - args: args - }; - }, - unsubscribe: function( id ) { - var channel = id && id.channel || jQuery.Channel( id ); - channel.unsubscribe.apply( channel, id && id.args || - sliceChannel.call( arguments, 1 ) ); - }, - publish: function( id ) { - var channel = jQuery.Channel( id ); - channel.publish.apply( channel, sliceChannel.call( arguments, 1 ) ); - } - }); - -})( jQuery ); diff --git a/src/topic.js b/src/topic.js new file mode 100644 index 00000000..c856db8c --- /dev/null +++ b/src/topic.js @@ -0,0 +1,45 @@ +(function( jQuery ) { + + var topics = {}, + sliceTopic = [].slice; + + jQuery.Topic = function( id ) { + var callbacks, + method, + topic = id && topics[ id ]; + if ( !topic ) { + callbacks = jQuery.Callbacks(); + topic = { + publish: callbacks.fire, + subscribe: callbacks.add, + unsubscribe: callbacks.remove + }; + if ( id ) { + topics[ id ] = topic; + } + } + return topic; + }; + + jQuery.extend({ + subscribe: function( id ) { + var topic = jQuery.Topic( id ), + args = sliceTopic.call( arguments, 1 ); + topic.subscribe.apply( topic, args ); + return { + topic: topic, + args: args + }; + }, + unsubscribe: function( id ) { + var topic = id && id.topic || jQuery.Topic( id ); + topic.unsubscribe.apply( topic, id && id.args || + sliceTopic.call( arguments, 1 ) ); + }, + publish: function( id ) { + var topic = jQuery.Topic( id ); + topic.publish.apply( topic, sliceTopic.call( arguments, 1 ) ); + } + }); + +})( jQuery ); diff --git a/test/index.html b/test/index.html index 6ddd3b5c..1c5ff2fe 100644 --- a/test/index.html +++ b/test/index.html @@ -10,7 +10,7 @@ - + @@ -38,7 +38,7 @@ - + diff --git a/test/unit/channel.js b/test/unit/topic.js similarity index 63% rename from test/unit/channel.js rename to test/unit/topic.js index b5e7a726..0b126fe3 100644 --- a/test/unit/channel.js +++ b/test/unit/topic.js @@ -1,10 +1,10 @@ -module("channel", { teardown: moduleTeardown }); +module("topic", { teardown: moduleTeardown }); -test( "jQuery.Channel - Anonymous Channel", function() { +test( "jQuery.Topic - Anonymous Topic", function() { expect( 4 ); - var channel = jQuery.Channel(), + var topic = jQuery.Topic(), count = 0; function firstCallback( value ) { @@ -13,19 +13,19 @@ test( "jQuery.Channel - Anonymous Channel", function() { } count++; - channel.subscribe( firstCallback ); - channel.publish( "test" ); - channel.unsubscribe( firstCallback ); + topic.subscribe( firstCallback ); + topic.publish( "test" ); + topic.unsubscribe( firstCallback ); count++; - channel.subscribe(function( value ) { + topic.subscribe(function( value ) { strictEqual( count, 2, "Callback called when needed" ); strictEqual( value, "test", "Published value received" ); }); - channel.publish( "test" ); + topic.publish( "test" ); }); -test( "jQuery.Channel - Named Channel", function() { +test( "jQuery.Topic - Named Topic", function() { expect( 2 ); @@ -34,13 +34,13 @@ test( "jQuery.Channel - Named Channel", function() { strictEqual( value, "test", "Proper value received" ); } - jQuery.Channel( "test" ).subscribe( callback ); - jQuery.Channel( "test" ).publish( "test" ); - jQuery.Channel( "test" ).unsubscribe( callback ); - jQuery.Channel( "test" ).publish( "test" ); + jQuery.Topic( "test" ).subscribe( callback ); + jQuery.Topic( "test" ).publish( "test" ); + jQuery.Topic( "test" ).unsubscribe( callback ); + jQuery.Topic( "test" ).publish( "test" ); }); -test( "jQuery.Channel - Helpers", function() { +test( "jQuery.Topic - Helpers", function() { expect( 4 ); From a31195fd5a86880963c5d2fd8af7f544faafdc62 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 6 May 2011 18:35:08 +0200 Subject: [PATCH 18/66] Replaces jQuery._Deferred with the much more flexible (and public) jQuery.Callbacks. Hopefully, jQuery.Callbacks can be used as a base for all callback lists needs in jQuery. Also adds progress callbacks to Deferreds (handled in jQuery.when too). Needs more unit tests. --- Makefile | 1 + src/ajax.js | 6 +- src/callbacks.js | 206 +++++++++++++++++++++++++++++ src/core.js | 8 +- src/deferred.js | 229 ++++++++++++--------------------- src/queue.js | 16 +-- test/data/offset/absolute.html | 2 +- test/data/offset/body.html | 2 +- test/data/offset/fixed.html | 2 +- test/data/offset/relative.html | 2 +- test/data/offset/scroll.html | 2 +- test/data/offset/static.html | 2 +- test/data/offset/table.html | 2 +- test/index.html | 4 +- test/unit/deferred.js | 106 --------------- 15 files changed, 317 insertions(+), 273 deletions(-) create mode 100644 src/callbacks.js diff --git a/Makefile b/Makefile index 06cee5de..3bb56e3d 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,7 @@ COMPILER = ${JS_ENGINE} ${BUILD_DIR}/uglify.js --unsafe POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ + ${SRC_DIR}/callbacks.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/ajax.js b/src/ajax.js index a16717b0..b9be5eb1 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -382,7 +382,7 @@ jQuery.extend({ jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), - completeDeferred = jQuery._Deferred(), + completeCallbacks = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key @@ -560,7 +560,7 @@ jQuery.extend({ } // Complete - completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); + completeCallbacks.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] ); @@ -575,7 +575,7 @@ jQuery.extend({ deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; - jqXHR.complete = completeDeferred.done; + jqXHR.complete = completeCallbacks.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { diff --git a/src/callbacks.js b/src/callbacks.js new file mode 100644 index 00000000..5d5eb98e --- /dev/null +++ b/src/callbacks.js @@ -0,0 +1,206 @@ +(function( jQuery ) { + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * filter: an optional function that will be applied to each added callbacks, + * what filter returns will then be added provided it is not falsy. + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * relocate: like "unique" but will relocate the callback at the end of the list + * + */ +jQuery.Callbacks = function( flags, filter ) { + + // flags are optional + if ( typeof flags !== "string" ) { + filter = flags; + flags = undefined; + } + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !flags.once && [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // Add a list of callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // If we have to relocate, we remove the callback + // if it already exists + if ( flags.relocate ) { + object.remove( elem ); + } + // Unless we have a list with unicity and the + // function is already there, add it + if ( !( flags.unique && object.has( elem ) ) ) { + // Get the filtered function if needs be + actual = filter ? filter(elem) : elem; + if ( actual ) { + list.push( [ elem, actual ] ); + } + } + } + } + }, + object = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + add( arguments ); + // If we're not firing and we should call right away + if ( !firing && flags.memory && memory ) { + // Trick the list into thinking it needs to be fired + var tmp = memory; + memory = undefined; + object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + list.splice( i, 1 ); + i--; + // If we have some unicity property then + // we only need to do this once + if ( flags.unique || flags.relocate ) { + break; + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + object.disable(); + } + return this; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + var i; + if ( list && ( flags.once ? !memory && !firing : stack ) ) { + if ( firing ) { + stack.push( [ context, args ] ); + } else { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + try { + for ( i = 0; list && i < list.length; i++ ) { + if ( list[ i ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + break; + } + } + } finally { + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( i >= list.length && stack.length ) { + object.fire.apply( this, stack.shift() ); + } + } else if ( !flags.memory ) { + object.destroy(); + } else { + list = []; + } + } + } + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + object.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return object; +}; + +})( jQuery ); diff --git a/src/core.js b/src/core.js index 3a32d6f0..f68675ce 100644 --- a/src/core.js +++ b/src/core.js @@ -58,7 +58,7 @@ var jQuery = function( selector, context ) { // For matching the engine and version of the browser browserMatch, - // The deferred used on DOM ready + // The callback list used on DOM ready readyList, // The ready event handler @@ -257,7 +257,7 @@ jQuery.fn = jQuery.prototype = { jQuery.bindReady(); // Add the callback - readyList.done( fn ); + readyList.add( fn ); return this; }, @@ -412,7 +412,7 @@ jQuery.extend({ } // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); + readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { @@ -426,7 +426,7 @@ jQuery.extend({ return; } - readyList = jQuery._Deferred(); + readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. diff --git a/src/deferred.js b/src/deferred.js index 5cc5fb5b..fb12866f 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -1,169 +1,105 @@ (function( jQuery ) { var // Promise methods - promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), + promiseMethods = "done fail progress isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ - // Create a simple deferred (one callbacks list) - _Deferred: function() { - var // callbacks list - callbacks = [], - // stored [ context , args ] - fired, - // to avoid firing when already doing so - 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 ) { - _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 ); + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + promise, + deferred = { + // Copy existing methods from lists + done: doneList.add, + removeDone: doneList.remove, + fail: failList.add, + removeFail: failList.remove, + progress: progressList.add, + removeProgress: progressList.remove, + resolve: doneList.fire, + resolveWith: doneList.fireWith, + reject: failList.fire, + rejectWith: failList.fireWith, + ping: progressList.fire, + pingWith: progressList.pingWith, + isResolved: doneList.fired, + isRejected: failList.fired, + + // Create Deferred-specific methods + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "ping" ] + }, 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, newDefer.ping ); + } 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 ) { + if ( obj == null ) { + if ( promise ) { + return promise; } - if ( _fired ) { - deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); - } + promise = obj = {}; } - return this; - }, - - // resolve with given context and args - resolveWith: function( context, args ) { - if ( !cancelled && !fired && !firing ) { - // make sure args are available (#8421) - args = args || []; - firing = 1; - try { - while( callbacks[ 0 ] ) { - callbacks.shift().apply( context, args ); - } - } - finally { - fired = [ context, args ]; - firing = 0; - } + var i = promiseMethods.length; + while( i-- ) { + obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } - return this; - }, - - // resolve with this as context and given arguments - resolve: function() { - deferred.resolveWith( this, arguments ); - return this; - }, - - // Has this deferred been resolved? - isResolved: function() { - return !!( firing || fired ); - }, - - // Cancel - cancel: function() { - cancelled = 1; - callbacks = []; - return this; + return obj; } }; - return deferred; - }, + // Handle lists exclusiveness + deferred.done( failList.disable, progressList.lock ) + .fail( doneList.disable, progressList.lock ); - // Full fledged deferred (two callbacks list) - Deferred: function( func ) { - var deferred = jQuery._Deferred(), - failDeferred = jQuery._Deferred(), - promise; - // Add errorDeferred methods, then and promise - jQuery.extend( deferred, { - then: function( doneCallbacks, failCallbacks ) { - 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, - pipe: 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 ( returned && 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 ) { - if ( obj == null ) { - if ( promise ) { - return promise; - } - promise = obj = {}; - } - var i = promiseMethods.length; - while( i-- ) { - obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; - } - return obj; - } - }); - // Make sure only one callback list will be used - deferred.done( failDeferred.cancel ).fail( deferred.cancel ); - // Unexpose cancel - delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } + + // All done! return deferred; }, // Deferred helper when: function( firstParam ) { - var args = arguments, + var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, + pValues = new Array( length ), count = length, + pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); @@ -171,17 +107,22 @@ jQuery.extend({ return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { - // Strange bug in FF4: - // Values changed onto the arguments object sometimes end up as undefined values - // outside the $.when method. Cloning the object into a fresh array solves the issue - deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.pingWith( deferred, pValue ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { - if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject ); + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } diff --git a/src/queue.js b/src/queue.js index 66383c19..145bfd6f 100644 --- a/src/queue.js +++ b/src/queue.js @@ -1,7 +1,7 @@ (function( jQuery ) { -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", +function handleCBList( elem, type, src ) { + var deferDataKey = type + "cblst", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); @@ -14,7 +14,7 @@ function handleQueueMarkDefer( elem, type, src ) { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); - defer.resolve(); + defer.fireWith(); } }, 0 ); } @@ -43,7 +43,7 @@ jQuery.extend({ jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); + handleCBList( elem, type, "mark" ); } } }, @@ -90,7 +90,7 @@ jQuery.extend({ if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); - handleQueueMarkDefer( elem, type, "queue" ); + handleCBList( elem, type, "queue" ); } } }); @@ -146,7 +146,7 @@ jQuery.fn.extend({ elements = this, i = elements.length, count = 1, - deferDataKey = type + "defer", + deferDataKey = type + "cblst", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; @@ -159,9 +159,9 @@ jQuery.fn.extend({ if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; - tmp.done( resolve ); + tmp.add( resolve ); } } resolve(); diff --git a/test/data/offset/absolute.html b/test/data/offset/absolute.html index 9d7990a3..2002a535 100644 --- a/test/data/offset/absolute.html +++ b/test/data/offset/absolute.html @@ -16,7 +16,7 @@ #positionTest { position: absolute; } - + diff --git a/test/data/offset/body.html b/test/data/offset/body.html index 8dbf282d..a661637f 100644 --- a/test/data/offset/body.html +++ b/test/data/offset/body.html @@ -9,7 +9,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/fixed.html b/test/data/offset/fixed.html index 81ba4ca7..c6eb9277 100644 --- a/test/data/offset/fixed.html +++ b/test/data/offset/fixed.html @@ -13,7 +13,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/relative.html b/test/data/offset/relative.html index 280a2fc0..6386eebd 100644 --- a/test/data/offset/relative.html +++ b/test/data/offset/relative.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/scroll.html b/test/data/offset/scroll.html index a0d1f4d1..0890d0ad 100644 --- a/test/data/offset/scroll.html +++ b/test/data/offset/scroll.html @@ -14,7 +14,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/static.html b/test/data/offset/static.html index a61b6d10..687e93e8 100644 --- a/test/data/offset/static.html +++ b/test/data/offset/static.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/data/offset/table.html b/test/data/offset/table.html index 11fb0e79..06774325 100644 --- a/test/data/offset/table.html +++ b/test/data/offset/table.html @@ -11,7 +11,7 @@ #marker { position: absolute; border: 2px solid #000; width: 50px; height: 50px; background: #ccc; } - + diff --git a/test/index.html b/test/index.html index 4b4c9855..bb563846 100644 --- a/test/index.html +++ b/test/index.html @@ -9,6 +9,7 @@ + @@ -34,8 +35,9 @@ - + + diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 89c9c612..0d8ef77c 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -1,111 +1,5 @@ module("deferred", { teardown: moduleTeardown }); -jQuery.each( [ "", " - new operator" ], function( _, withNew ) { - - function createDeferred() { - return withNew ? new jQuery._Deferred() : jQuery._Deferred(); - } - - test("jQuery._Deferred" + withNew, function() { - - expect( 11 ); - - var deferred, - object, - test; - - deferred = createDeferred(); - - test = false; - - deferred.done( function( value ) { - equals( value , "value" , "Test pre-resolve callback" ); - test = true; - } ); - - deferred.resolve( "value" ); - - ok( test , "Test pre-resolve callbacks called right away" ); - - test = false; - - deferred.done( function( value ) { - equals( value , "value" , "Test post-resolve callback" ); - test = true; - } ); - - ok( test , "Test post-resolve callbacks called right away" ); - - deferred.cancel(); - - test = true; - - deferred.done( function() { - ok( false , "Cancel was ignored" ); - test = false; - } ); - - ok( test , "Test cancel" ); - - deferred = createDeferred().resolve(); - - try { - deferred.done( function() { - throw "Error"; - } , function() { - ok( true , "Test deferred do not cancel on exception" ); - } ); - } catch( e ) { - strictEqual( e , "Error" , "Test deferred propagates exceptions"); - deferred.done(); - } - - test = ""; - deferred = createDeferred().done( function() { - - test += "A"; - - }, function() { - - test += "B"; - - } ).resolve(); - - strictEqual( test , "AB" , "Test multiple done parameters" ); - - test = ""; - - deferred.done( function() { - - deferred.done( function() { - - test += "C"; - - } ); - - test += "A"; - - }, function() { - - test += "B"; - } ); - - strictEqual( test , "ABC" , "Test done callbacks order" ); - - deferred = createDeferred(); - - deferred.resolveWith( jQuery , [ document ] ).done( function( doc ) { - ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" ); - }); - - // #8421 - deferred = createDeferred(); - deferred.resolveWith().done(function() { - ok( true, "Test resolveWith can be called with no argument" ); - }); - }); -} ); - jQuery.each( [ "", " - new operator" ], function( _, withNew ) { function createDeferred( fn ) { From 5ee68d6b137bc8a8c4a1afb388ef8acdf4fcf52e Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 00:23:00 +0200 Subject: [PATCH 19/66] Added stopOnFalse method description in comments and reformatted then in the process. --- src/callbacks.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index 5d5eb98e..ab700887 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -28,15 +28,17 @@ function createFlags( flags ) { * * Possible flags: * - * once: will ensure the callback list can only be fired once (like a Deferred) + * once: will ensure the callback list can only be fired once (like a Deferred) * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) * - * unique: will ensure a callback can only be added once (no duplicate in the list) + * unique: will ensure a callback can only be added once (no duplicate in the list) * - * relocate: like "unique" but will relocate the callback at the end of the list + * relocate: like "unique" but will relocate the callback at the end of the list + * + * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags, filter ) { From 142ae3e08a612e9c51c6ab9d9b3595a068c966f2 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 03:38:54 +0200 Subject: [PATCH 20/66] First bunch of unit tests for jQuery.Callbacks. --- test/unit/callbacks.js | 180 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 test/unit/callbacks.js diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js new file mode 100644 index 00000000..2f45337e --- /dev/null +++ b/test/unit/callbacks.js @@ -0,0 +1,180 @@ +module("callbacks", { teardown: moduleTeardown }); + +(function() { + +var output, + addToOutput = function( string ) { + return function() { + output += string; + }; + }, + outputA = addToOutput( "A" ), + outputB = addToOutput( "B" ), + outputC = addToOutput( "C" ), + tests = { + "": "X XABCABCC X XBB X", + "once": "X X X X X", + "memory": "XABC XABCABCCC XA XBB XB", + "unique": "X XABCA X XBB X", + "relocate": "X XAABC X XBB X", + "stopOnFalse": "X XABCABCC X XBB X", + "once memory": "XABC X XA X XA", + "once unique": "X X X X X", + "once relocate": "X X X X X", + "once stopOnFalse": "X X X X X", + "memory unique": "XA XABCA XA XBB XB", + "memory relocate": "XB XAABC XA XBB XB", + "memory stopOnFalse": "XABC XABCABCCC XA XBB XB", + "unique relocate": "X XAABC X XBB X", + "unique stopOnFalse": "X XABCA X XBB X", + "relocate stopOnFalse": "X XAABC X XBB X" + }, + filters = { + "no filter": undefined, + "filter": function( fn ) { + return function() { + return fn.apply( this, arguments ); + }; + } + }; + +jQuery.each( tests, function( flags, resultString ) { + + function createList() { + return jQuery.Callbacks( flags ); + } + + jQuery.each( filters, function( filterLabel, filter ) { + + test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { + + expect( 17 ); + + // Give qunit a little breathing room + stop(); + setTimeout( start, 0 ); + + var cblist; + results = resultString.split( /\s+/ ); + + // Basic binding and firing + output = "X"; + cblist = createList(); + cblist.add(function( str ) { + output += str; + }); + cblist.fire( "A" ); + strictEqual( output, "XA", "Basic binding and firing" ); + output = "X"; + cblist.disable(); + cblist.add(function( str ) { + output += str; + }); + strictEqual( output, "X", "Adding a callback after disabling" ); + cblist.fire( "A" ); + strictEqual( output, "X", "Firing after disabling" ); + + // Basic binding and firing (context, arguments) + output = "X"; + cblist = createList(); + cblist.add(function() { + equals( this, window, "Basic binding and firing (context)" ); + output += Array.prototype.join.call( arguments, "" ); + }); + cblist.fireWith( window, [ "A", "B" ] ); + strictEqual( output, "XAB", "Basic binding and firing (arguments)" ); + + // fireWith with no arguments + output = ""; + cblist = createList(); + cblist.add(function() { + equals( this, window, "fireWith with no arguments (context is window)" ); + strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" ); + }); + cblist.fireWith(); + + // Basic binding, removing and firing + output = "X"; + cblist = createList(); + cblist.add( outputA ); + cblist.add( outputB ); + cblist.add( outputC ); + cblist.remove( outputB ); + cblist.fire(); + strictEqual( output, "XAC", "Basic binding, removing and firing" ); + + // Empty + output = "X"; + cblist = createList(); + cblist.add( outputA ); + cblist.add( outputB ); + cblist.add( outputC ); + cblist.empty(); + cblist.fire(); + strictEqual( output, "X", "Empty" ); + + // Locking + output = "X"; + cblist = createList(); + cblist.add( function( str ) { + output += str; + }); + cblist.lock(); + cblist.add( function( str ) { + output += str; + }); + cblist.fire( "A" ); + cblist.add( function( str ) { + output += str; + }); + strictEqual( output, "X", "Lock early" ); + + // Ordering + output = "X"; + cblist = createList(); + cblist.add( function() { + cblist.add( outputC ); + outputA(); + }, outputB ); + cblist.fire(); + strictEqual( output, "XABC", "Proper ordering" ); + + // Add and fire again + output = "X"; + cblist.add( function() { + cblist.add( outputC ); + outputA(); + }, outputB ); + strictEqual( output, results.shift(), "Add after fire" ); + + output = "X"; + cblist.fire(); + strictEqual( output, results.shift(), "Fire again" ); + + // Multiple fire + output = "X"; + cblist = createList(); + cblist.add( function( str ) { + output += str; + } ); + cblist.fire( "A" ); + strictEqual( output, "XA", "Multiple fire (first fire)" ); + output = "X"; + cblist.add( function( str ) { + output += str; + } ); + strictEqual( output, results.shift(), "Multiple fire (first new callback)" ); + output = "X"; + cblist.fire( "B" ); + strictEqual( output, results.shift(), "Multiple fire (second fire)" ); + output = "X"; + cblist.add( function( str ) { + output += str; + } ); + strictEqual( output, results.shift(), "Multiple fire (second new callback)" ); + + }); + }); +}); + +})(); From 03c4fe9da98ce4753b012f1f370018d15fa2118c Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sat, 7 May 2011 03:39:41 +0200 Subject: [PATCH 21/66] Fixes for bugs found thanks to unit tests. --- src/callbacks.js | 62 ++++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index ab700887..62e27d2b 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -56,11 +56,13 @@ jQuery.Callbacks = function( flags, filter ) { var // Actual callback list list = [], // Stack of fire calls for repeatable lists - stack = !flags.once && [], + stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, + // Index of cells to remove in the list after firing + deleteAfterFire, // Add a list of callbacks to the list add = function( args ) { var i, @@ -79,15 +81,13 @@ jQuery.Callbacks = function( flags, filter ) { // if it already exists if ( flags.relocate ) { object.remove( elem ); + } else if ( flags.unique && object.has( elem ) ) { + continue; } - // Unless we have a list with unicity and the - // function is already there, add it - if ( !( flags.unique && object.has( elem ) ) ) { - // Get the filtered function if needs be - actual = filter ? filter(elem) : elem; - if ( actual ) { - list.push( [ elem, actual ] ); - } + // Get the filtered function if needs be + actual = filter ? filter( elem ) : elem; + if ( actual ) { + list.push( [ elem, actual ] ); } } } @@ -96,13 +96,15 @@ jQuery.Callbacks = function( flags, filter ) { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { + var length = list.length; add( arguments ); - // If we're not firing and we should call right away + // With memory, if we're not firing then + // we should call right away if ( !firing && flags.memory && memory ) { // Trick the list into thinking it needs to be fired var tmp = memory; memory = undefined; - object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + object.fireWith( tmp[ 0 ], tmp[ 1 ], length ); } } return this; @@ -113,9 +115,14 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { - list.splice( i, 1 ); - i--; + if ( list[ i ] && fn === list[ i ][ 0 ] ) { + if ( firing ) { + list[ i ] = undefined; + deleteAfterFire.push( i ); + } else { + list.splice( i, 1 ); + i--; + } // If we have some unicity property then // we only need to do this once if ( flags.unique || flags.relocate ) { @@ -132,7 +139,7 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { + if ( list[ i ] && fn === list[ i ][ 0 ] ) { return true; } } @@ -158,30 +165,39 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - var i; - if ( list && ( flags.once ? !memory && !firing : stack ) ) { + fireWith: function( context, args, start /* internal */ ) { + var i, + done, + stoppedOnFalse; + if ( list && stack && ( !flags.once || !memory && !firing ) ) { if ( firing ) { stack.push( [ context, args ] ); } else { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; + deleteAfterFire = []; try { - for ( i = 0; list && i < list.length; i++ ) { - if ( list[ i ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + for ( i = start || 0; list && i < list.length; i++ ) { + if (( stoppedOnFalse = list[ i ] && + list[ i ][ 1 ].apply( context, args ) === false && + flags.stopOnFalse )) { break; } } } finally { firing = false; if ( list ) { + done = ( stoppedOnFalse || i >= list.length ); + for ( i = 0; i < deleteAfterFire.length; i++ ) { + list.splice( deleteAfterFire[ i ], 1 ); + } if ( !flags.once ) { - if ( i >= list.length && stack.length ) { - object.fire.apply( this, stack.shift() ); + if ( done && stack && stack.length ) { + object.fireWith.apply( this, stack.shift() ); } } else if ( !flags.memory ) { - object.destroy(); + object.disable(); } else { list = []; } From 198290a9a744f01c8604e796b8e34e06fec6bf03 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 16:11:00 +0200 Subject: [PATCH 22/66] Simplifies how removal when firing is handled. Removes exception handling (lets the list deadlock). Makes sure no external code can fire the list from a given index (only possible internally). --- src/callbacks.js | 72 ++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 42 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index 62e27d2b..e0a70fed 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -61,8 +61,10 @@ jQuery.Callbacks = function( flags, filter ) { memory, // Flag to know if list is currently firing firing, - // Index of cells to remove in the list after firing - deleteAfterFire, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Index of currently firing callback (modified by remove if needed) + firingIndex, // Add a list of callbacks to the list add = function( args ) { var i, @@ -101,10 +103,10 @@ jQuery.Callbacks = function( flags, filter ) { // With memory, if we're not firing then // we should call right away if ( !firing && flags.memory && memory ) { - // Trick the list into thinking it needs to be fired var tmp = memory; memory = undefined; - object.fireWith( tmp[ 0 ], tmp[ 1 ], length ); + firingStart = length; + object.fireWith( tmp[ 0 ], tmp[ 1 ] ); } } return this; @@ -112,17 +114,14 @@ jQuery.Callbacks = function( flags, filter ) { // Remove a callback from the list remove: function( fn ) { if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( list[ i ] && fn === list[ i ][ 0 ] ) { - if ( firing ) { - list[ i ] = undefined; - deleteAfterFire.push( i ); - } else { - list.splice( i, 1 ); - i--; + for ( var i = 0; i < list.length; i++ ) { + if ( fn === list[ i ][ 0 ] ) { + // Handle firingIndex + if ( firing && i <= firingIndex ) { + firingIndex--; } + // Remove the element + list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique || flags.relocate ) { @@ -139,7 +138,7 @@ jQuery.Callbacks = function( flags, filter ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { - if ( list[ i ] && fn === list[ i ][ 0 ] ) { + if ( fn === list[ i ][ 0 ] ) { return true; } } @@ -165,10 +164,9 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Call all callbacks with the given context and arguments - fireWith: function( context, args, start /* internal */ ) { - var i, - done, - stoppedOnFalse; + fireWith: function( context, args ) { + var start = firingStart; + firingStart = 0; if ( list && stack && ( !flags.once || !memory && !firing ) ) { if ( firing ) { stack.push( [ context, args ] ); @@ -176,31 +174,21 @@ jQuery.Callbacks = function( flags, filter ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; - deleteAfterFire = []; - try { - for ( i = start || 0; list && i < list.length; i++ ) { - if (( stoppedOnFalse = list[ i ] && - list[ i ][ 1 ].apply( context, args ) === false && - flags.stopOnFalse )) { - break; - } + for ( firingIndex = start || 0; list && firingIndex < list.length; firingIndex++ ) { + if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + break; } - } finally { - firing = false; - if ( list ) { - done = ( stoppedOnFalse || i >= list.length ); - for ( i = 0; i < deleteAfterFire.length; i++ ) { - list.splice( deleteAfterFire[ i ], 1 ); - } - if ( !flags.once ) { - if ( done && stack && stack.length ) { - object.fireWith.apply( this, stack.shift() ); - } - } else if ( !flags.memory ) { - object.disable(); - } else { - list = []; + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + object.fireWith.apply( this, stack.shift() ); } + } else if ( !flags.memory ) { + object.disable(); + } else { + list = []; } } } From 3a6b759d3c36e126bb99c85f1ce969cb59498ff9 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 16:12:43 +0200 Subject: [PATCH 23/66] Removes definition of createList and use jQuery.Callbacks directly to make things a bit less obfuscated. --- test/unit/callbacks.js | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index 2f45337e..c47c4b13 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -40,10 +40,6 @@ var output, jQuery.each( tests, function( flags, resultString ) { - function createList() { - return jQuery.Callbacks( flags ); - } - jQuery.each( filters, function( filterLabel, filter ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { @@ -59,7 +55,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding and firing output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function( str ) { output += str; }); @@ -76,7 +72,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding and firing (context, arguments) output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function() { equals( this, window, "Basic binding and firing (context)" ); output += Array.prototype.join.call( arguments, "" ); @@ -86,7 +82,7 @@ jQuery.each( tests, function( flags, resultString ) { // fireWith with no arguments output = ""; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add(function() { equals( this, window, "fireWith with no arguments (context is window)" ); strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" ); @@ -95,7 +91,7 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding, removing and firing output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( outputA ); cblist.add( outputB ); cblist.add( outputC ); @@ -105,7 +101,7 @@ jQuery.each( tests, function( flags, resultString ) { // Empty output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( outputA ); cblist.add( outputB ); cblist.add( outputC ); @@ -115,7 +111,7 @@ jQuery.each( tests, function( flags, resultString ) { // Locking output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; }); @@ -131,7 +127,7 @@ jQuery.each( tests, function( flags, resultString ) { // Ordering output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function() { cblist.add( outputC ); outputA(); @@ -153,7 +149,7 @@ jQuery.each( tests, function( flags, resultString ) { // Multiple fire output = "X"; - cblist = createList(); + cblist = jQuery.Callbacks( flags ); cblist.add( function( str ) { output += str; } ); From 946a9204a15761b42ae27f5807d4280948c527e4 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 18:38:00 +0200 Subject: [PATCH 24/66] Adds disabled and locked. Simplifies logic in fireWith. --- src/callbacks.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index e0a70fed..dc7e176f 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -83,6 +83,7 @@ jQuery.Callbacks = function( flags, filter ) { // if it already exists if ( flags.relocate ) { object.remove( elem ); + // Skip if we're in unique mode and callback is already in } else if ( flags.unique && object.has( elem ) ) { continue; } @@ -155,6 +156,10 @@ jQuery.Callbacks = function( flags, filter ) { list = stack = memory = undefined; return this; }, + // Is it disabled? + disabled: function() { + return !list; + }, // Lock the list in its current state lock: function() { stack = undefined; @@ -163,18 +168,24 @@ jQuery.Callbacks = function( flags, filter ) { } return this; }, + // Is it locked? + locked: function() { + return !stack; + }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { - var start = firingStart; - firingStart = 0; - if ( list && stack && ( !flags.once || !memory && !firing ) ) { + if ( list ) { if ( firing ) { - stack.push( [ context, args ] ); - } else { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { args = args || []; - memory = !flags.memory || [ context, args ]; + memory = [ context, args ]; firing = true; - for ( firingIndex = start || 0; list && firingIndex < list.length; firingIndex++ ) { + firingIndex = firingStart || 0; + firingStart = 0; + for ( ; list && firingIndex < list.length; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { break; } @@ -183,7 +194,8 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { - object.fireWith.apply( this, stack.shift() ); + memory = stack.shift(); + object.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( !flags.memory ) { object.disable(); From 8dcf7ec1ce05ab5e10207b0838be91181fd41fdc Mon Sep 17 00:00:00 2001 From: jaubourg Date: Sun, 8 May 2011 20:02:34 +0200 Subject: [PATCH 25/66] Adds addAfterFire flag. Unit tests updated with addAfterFire cases and also for when a callback returns false. --- src/callbacks.js | 27 ++++++++++++++++++----- test/unit/callbacks.js | 49 ++++++++++++++++++++++++++---------------- 2 files changed, 53 insertions(+), 23 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index dc7e176f..f0c0ca38 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -40,6 +40,9 @@ function createFlags( flags ) { * * stopOnFalse: interrupt callings when a callback returns false * + * addAfterFire: if callbacks are added while firing, then they are not executed until after + * the next call to fire/fireWith + * */ jQuery.Callbacks = function( flags, filter ) { @@ -63,6 +66,8 @@ jQuery.Callbacks = function( flags, filter ) { firing, // First callback to fire (used internally by add and fireWith) firingStart, + // End of the loop when firing + firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add a list of callbacks to the list @@ -101,9 +106,15 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { var length = list.length; add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + if ( !flags.addAfterFire ) { + firingLength = list.length; + } // With memory, if we're not firing then // we should call right away - if ( !firing && flags.memory && memory ) { + } else if ( flags.memory && memory ) { var tmp = memory; memory = undefined; firingStart = length; @@ -117,9 +128,14 @@ jQuery.Callbacks = function( flags, filter ) { if ( list ) { for ( var i = 0; i < list.length; i++ ) { if ( fn === list[ i ][ 0 ] ) { - // Handle firingIndex - if ( firing && i <= firingIndex ) { - firingIndex--; + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } } // Remove the element list.splice( i--, 1 ); @@ -185,7 +201,8 @@ jQuery.Callbacks = function( flags, filter ) { firing = true; firingIndex = firingStart || 0; firingStart = 0; - for ( ; list && firingIndex < list.length; firingIndex++ ) { + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { break; } diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index c47c4b13..860a7cbb 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -12,22 +12,28 @@ var output, outputB = addToOutput( "B" ), outputC = addToOutput( "C" ), tests = { - "": "X XABCABCC X XBB X", - "once": "X X X X X", - "memory": "XABC XABCABCCC XA XBB XB", - "unique": "X XABCA X XBB X", - "relocate": "X XAABC X XBB X", - "stopOnFalse": "X XABCABCC X XBB X", - "once memory": "XABC X XA X XA", - "once unique": "X X X X X", - "once relocate": "X X X X X", - "once stopOnFalse": "X X X X X", - "memory unique": "XA XABCA XA XBB XB", - "memory relocate": "XB XAABC XA XBB XB", - "memory stopOnFalse": "XABC XABCABCCC XA XBB XB", - "unique relocate": "X XAABC X XBB X", - "unique stopOnFalse": "X XABCA X XBB X", - "relocate stopOnFalse": "X XAABC X XBB X" + "": "XABC X XABCABCC X XBB X XABA", + "once": "XABC X X X X X XABA", + "memory": "XABC XABC XABCABCCC XA XBB XB XABA", + "unique": "XABC X XABCA X XBB X XAB", + "relocate": "XABC X XAABC X XBB X XBA", + "stopOnFalse": "XABC X XABCABCC X XBB X XA", + "addAfterFire": "XAB X XABCAB X XBB X XABA", + "once memory": "XABC XABC X XA X XA XABA", + "once unique": "XABC X X X X X XAB", + "once relocate": "XABC X X X X X XBA", + "once stopOnFalse": "XABC X X X X X XA", + "once addAfterFire": "XAB X X X X X XABA", + "memory unique": "XABC XA XABCA XA XBB XB XAB", + "memory relocate": "XABC XB XAABC XA XBB XB XBA", + "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA", + "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA", + "unique relocate": "XABC X XAABC X XBB X XBA", + "unique stopOnFalse": "XABC X XABCA X XBB X XA", + "unique addAfterFire": "XAB X XABCA X XBB X XAB", + "relocate stopOnFalse": "XABC X XAABC X XBB X X", + "relocate addAfterFire": "XAB X XAA X XBB X XBA", + "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA" }, filters = { "no filter": undefined, @@ -44,7 +50,7 @@ jQuery.each( tests, function( flags, resultString ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { - expect( 17 ); + expect( 18 ); // Give qunit a little breathing room stop(); @@ -133,7 +139,7 @@ jQuery.each( tests, function( flags, resultString ) { outputA(); }, outputB ); cblist.fire(); - strictEqual( output, "XABC", "Proper ordering" ); + strictEqual( output, results.shift(), "Proper ordering" ); // Add and fire again output = "X"; @@ -169,6 +175,13 @@ jQuery.each( tests, function( flags, resultString ) { } ); strictEqual( output, results.shift(), "Multiple fire (second new callback)" ); + // Return false + output = "X"; + cblist = jQuery.Callbacks( flags ); + cblist.add( outputA, function() { return false; }, outputB ); + cblist.add( outputA ); + cblist.fire(); + strictEqual( output, results.shift(), "Callback returning false" ); }); }); }); From ebb39c2774c270bb37ec15d54c0a2ff04eea052a Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 00:40:45 +0200 Subject: [PATCH 26/66] Ensures a list with memory will not called further callbacks before the next fire/fireWith is in stopOnFalse mode and a callback returned false. Unit tests added. --- src/callbacks.js | 12 ++++++---- test/unit/callbacks.js | 52 +++++++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index f0c0ca38..0d126f80 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -113,8 +113,9 @@ jQuery.Callbacks = function( flags, filter ) { firingLength = list.length; } // With memory, if we're not firing then - // we should call right away - } else if ( flags.memory && memory ) { + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { var tmp = memory; memory = undefined; firingStart = length; @@ -179,7 +180,7 @@ jQuery.Callbacks = function( flags, filter ) { // Lock the list in its current state lock: function() { stack = undefined; - if ( !memory ) { + if ( !memory || memory === true ) { object.disable(); } return this; @@ -197,13 +198,14 @@ jQuery.Callbacks = function( flags, filter ) { } } else if ( !( flags.once && memory ) ) { args = args || []; - memory = [ context, args ]; + memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted break; } } @@ -214,7 +216,7 @@ jQuery.Callbacks = function( flags, filter ) { memory = stack.shift(); object.fireWith( memory[ 0 ], memory[ 1 ] ); } - } else if ( !flags.memory ) { + } else if ( memory === true ) { object.disable(); } else { list = []; diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index 860a7cbb..f179a6b1 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -12,28 +12,28 @@ var output, outputB = addToOutput( "B" ), outputC = addToOutput( "C" ), tests = { - "": "XABC X XABCABCC X XBB X XABA", - "once": "XABC X X X X X XABA", - "memory": "XABC XABC XABCABCCC XA XBB XB XABA", - "unique": "XABC X XABCA X XBB X XAB", - "relocate": "XABC X XAABC X XBB X XBA", - "stopOnFalse": "XABC X XABCABCC X XBB X XA", - "addAfterFire": "XAB X XABCAB X XBB X XABA", - "once memory": "XABC XABC X XA X XA XABA", - "once unique": "XABC X X X X X XAB", - "once relocate": "XABC X X X X X XBA", - "once stopOnFalse": "XABC X X X X X XA", - "once addAfterFire": "XAB X X X X X XABA", - "memory unique": "XABC XA XABCA XA XBB XB XAB", - "memory relocate": "XABC XB XAABC XA XBB XB XBA", - "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA", - "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA", - "unique relocate": "XABC X XAABC X XBB X XBA", - "unique stopOnFalse": "XABC X XABCA X XBB X XA", - "unique addAfterFire": "XAB X XABCA X XBB X XAB", - "relocate stopOnFalse": "XABC X XAABC X XBB X X", - "relocate addAfterFire": "XAB X XAA X XBB X XBA", - "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA" + "": "XABC X XABCABCC X XBB X XABA X", + "once": "XABC X X X X X XABA X", + "memory": "XABC XABC XABCABCCC XA XBB XB XABA XC", + "unique": "XABC X XABCA X XBB X XAB X", + "relocate": "XABC X XAABC X XBB X XBA X", + "stopOnFalse": "XABC X XABCABCC X XBB X XA X", + "addAfterFire": "XAB X XABCAB X XBB X XABA X", + "once memory": "XABC XABC X XA X XA XABA XC", + "once unique": "XABC X X X X X XAB X", + "once relocate": "XABC X X X X X XBA X", + "once stopOnFalse": "XABC X X X X X XA X", + "once addAfterFire": "XAB X X X X X XABA X", + "memory unique": "XABC XA XABCA XA XBB XB XAB XC", + "memory relocate": "XABC XB XAABC XA XBB XB XBA XC", + "memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA X", + "memory addAfterFire": "XAB XAB XABCABC XA XBB XB XABA XC", + "unique relocate": "XABC X XAABC X XBB X XBA X", + "unique stopOnFalse": "XABC X XABCA X XBB X XA X", + "unique addAfterFire": "XAB X XABCA X XBB X XAB X", + "relocate stopOnFalse": "XABC X XAABC X XBB X X X", + "relocate addAfterFire": "XAB X XAA X XBB X XBA X", + "stopOnFalse addAfterFire": "XAB X XABCAB X XBB X XA X" }, filters = { "no filter": undefined, @@ -50,7 +50,7 @@ jQuery.each( tests, function( flags, resultString ) { test( "jQuery.Callbacks( \"" + flags + "\" ) - " + filterLabel, function() { - expect( 18 ); + expect( 19 ); // Give qunit a little breathing room stop(); @@ -182,6 +182,12 @@ jQuery.each( tests, function( flags, resultString ) { cblist.add( outputA ); cblist.fire(); strictEqual( output, results.shift(), "Callback returning false" ); + + // Add another callback (to control lists with memory do not fire anymore) + output = "X"; + cblist.add( outputC ); + strictEqual( output, results.shift(), "Adding a callback after one returned false" ); + }); }); }); From 05ae8f37b875057d94c89e0de72c0e5576cbb362 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 00:53:09 +0200 Subject: [PATCH 27/66] Makes sure repeatable lists with memory are properly locked. --- src/callbacks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/callbacks.js b/src/callbacks.js index 0d126f80..bf86575e 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -191,7 +191,7 @@ jQuery.Callbacks = function( flags, filter ) { }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { - if ( list ) { + if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); From a3a657cb2c8fee500ef0aabe1e7edb6f5460571b Mon Sep 17 00:00:00 2001 From: jaubourg Date: Mon, 9 May 2011 01:31:29 +0200 Subject: [PATCH 28/66] Add Deferred.progress() unit tests and fixes some progress related typos and bugs. --- src/deferred.js | 13 +++-- test/unit/deferred.js | 110 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 106 insertions(+), 17 deletions(-) diff --git a/src/deferred.js b/src/deferred.js index fb12866f..7592e361 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -1,7 +1,7 @@ (function( jQuery ) { var // Promise methods - promiseMethods = "done fail progress isResolved isRejected promise then always pipe".split( " " ), + promiseMethods = "done removeDone fail removeFail progress removeProgress isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; @@ -25,7 +25,7 @@ jQuery.extend({ reject: failList.fire, rejectWith: failList.fireWith, ping: progressList.fire, - pingWith: progressList.pingWith, + pingWith: progressList.fireWith, isResolved: doneList.fired, isRejected: failList.fired, @@ -102,7 +102,8 @@ jQuery.extend({ pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : - jQuery.Deferred(); + jQuery.Deferred(), + promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; @@ -114,9 +115,7 @@ jQuery.extend({ function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.pingWith( deferred, pValue ); - } + deferred.pingWith( promise, pValues ); }; } if ( length > 1 ) { @@ -133,7 +132,7 @@ jQuery.extend({ } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } - return deferred.promise(); + return promise; } }); diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 0d8ef77c..6e3cab89 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -8,7 +8,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { test("jQuery.Deferred" + withNew, function() { - expect( 8 ); + expect( 14 ); createDeferred().resolve().then( function() { ok( true , "Success on resolve" ); @@ -34,6 +34,20 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { }).then( function( value ) { strictEqual( value , "done" , "Passed function executed" ); }); + + jQuery.each( "resolve reject".split( " " ), function( _, change ) { + createDeferred( function( defer ) { + var checked = 0; + defer.progress(function( value ) { + strictEqual( value, checked, "Progress: right value (" + value + ") received" ) + }); + for( checked = 0; checked < 3 ; checked++ ) { + defer.ping( checked ); + } + defer[ change ](); + defer.ping(); + }); + }); }); } ); @@ -109,6 +123,34 @@ test( "jQuery.Deferred.pipe - filtering (fail)", function() { }); }); +test( "jQuery.Deferred.pipe - filtering (progress)", function() { + + expect(3); + + var defer = jQuery.Deferred(), + piped = defer.pipe( null, null, function( a, b ) { + return a * b; + } ), + value1, + value2, + value3; + + piped.progress(function( result ) { + value3 = result; + }); + + defer.progress(function( a, b ) { + value1 = a; + value2 = b; + }); + + defer.ping( 2, 3 ); + + strictEqual( value1, 2, "first reject value ok" ); + strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value3, 6, "result of filter ok" ); +}); + test( "jQuery.Deferred.pipe - deferred (done)", function() { expect(3); @@ -169,6 +211,36 @@ test( "jQuery.Deferred.pipe - deferred (fail)", function() { strictEqual( value3, 6, "result of filter ok" ); }); +test( "jQuery.Deferred.pipe - deferred (progress)", function() { + + expect(3); + + var defer = jQuery.Deferred(), + piped = defer.pipe( null, null, function( a, b ) { + return jQuery.Deferred(function( defer ) { + defer.resolve( a * b ); + }); + } ), + value1, + value2, + value3; + + piped.done(function( result ) { + value3 = result; + }); + + defer.progress(function( a, b ) { + value1 = a; + value2 = b; + }); + + defer.ping( 2, 3 ); + + strictEqual( value1, 2, "first reject value ok" ); + strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value3, 6, "result of filter ok" ); +}); + test( "jQuery.when" , function() { expect( 23 ); @@ -212,36 +284,54 @@ test( "jQuery.when" , function() { test("jQuery.when - joined", function() { - expect(25); + expect(50); var deferreds = { value: 1, success: jQuery.Deferred().resolve( 1 ), error: jQuery.Deferred().reject( 0 ), - futureSuccess: jQuery.Deferred(), - futureError: jQuery.Deferred() + futureSuccess: jQuery.Deferred().ping( true ), + futureError: jQuery.Deferred().ping( true ), + ping: jQuery.Deferred().ping( true ) }, willSucceed = { value: true, success: true, - error: false, + futureSuccess: true + }, + willError = { + error: true, + futureError: true + }, + willPing = { futureSuccess: true, - futureError: false + futureError: true, + ping: true }; jQuery.each( deferreds, function( id1, defer1 ) { jQuery.each( deferreds, function( id2, defer2 ) { var shouldResolve = willSucceed[ id1 ] && willSucceed[ id2 ], + shouldError = willError[ id1 ] || willError[ id2 ], + shouldPing = willPing[ id1 ] || willPing[ id2 ], expected = shouldResolve ? [ 1, 1 ] : [ 0, undefined ], - code = id1 + "/" + id2; - jQuery.when( defer1, defer2 ).done(function( a, b ) { + expectedPing = shouldPing && [ willPing[ id1 ], willPing[ id2 ] ], + code = id1 + "/" + id2; + + var promise = jQuery.when( defer1, defer2 ).done(function( a, b ) { if ( shouldResolve ) { same( [ a, b ], expected, code + " => resolve" ); + } else { + ok( false , code + " => resolve" ); } }).fail(function( a, b ) { - if ( !shouldResolve ) { - same( [ a, b ], expected, code + " => resolve" ); + if ( shouldError ) { + same( [ a, b ], expected, code + " => reject" ); + } else { + ok( false , code + " => reject" ); } + }).progress(function progress( a, b ) { + same( [ a, b ], expectedPing, code + " => progress" ); }); } ); } ); From 4f3f0e1d4ecf5d21c1e6bb01ef6f0e3be64d7959 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 01:03:30 +0200 Subject: [PATCH 29/66] Fixes repeatable callbacks list with memory disabling. Unit tests for Deferreds updated. --- src/callbacks.js | 57 ++++++++++++++++++++++--------------------- test/unit/deferred.js | 12 ++++----- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index bf86575e..b3635df7 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -100,6 +100,33 @@ jQuery.Callbacks = function( flags, filter ) { } } }, + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + object.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + object.disable(); + } else { + list = []; + } + } + }, object = { // Add a callback or a collection of callbacks to the list add: function() { @@ -116,10 +143,8 @@ jQuery.Callbacks = function( flags, filter ) { // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { - var tmp = memory; - memory = undefined; firingStart = length; - object.fireWith( tmp[ 0 ], tmp[ 1 ] ); + fire( memory[ 0 ], memory[ 1 ] ); } } return this; @@ -197,31 +222,7 @@ jQuery.Callbacks = function( flags, filter ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - object.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - object.disable(); - } else { - list = []; - } - } + fire( context, args ); } } return this; diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 6e3cab89..ed568799 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -39,7 +39,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) { createDeferred( function( defer ) { var checked = 0; defer.progress(function( value ) { - strictEqual( value, checked, "Progress: right value (" + value + ") received" ) + strictEqual( value, checked, "Progress: right value (" + value + ") received" ); }); for( checked = 0; checked < 3 ; checked++ ) { defer.ping( checked ); @@ -146,8 +146,8 @@ test( "jQuery.Deferred.pipe - filtering (progress)", function() { defer.ping( 2, 3 ); - strictEqual( value1, 2, "first reject value ok" ); - strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value1, 2, "first progress value ok" ); + strictEqual( value2, 3, "second progress value ok" ); strictEqual( value3, 6, "result of filter ok" ); }); @@ -236,8 +236,8 @@ test( "jQuery.Deferred.pipe - deferred (progress)", function() { defer.ping( 2, 3 ); - strictEqual( value1, 2, "first reject value ok" ); - strictEqual( value2, 3, "second reject value ok" ); + strictEqual( value1, 2, "first progress value ok" ); + strictEqual( value2, 3, "second progress value ok" ); strictEqual( value3, 6, "result of filter ok" ); }); @@ -284,7 +284,7 @@ test( "jQuery.when" , function() { test("jQuery.when - joined", function() { - expect(50); + expect(53); var deferreds = { value: 1, From 57634a2c159ccece07f203442b15c911e4ad88aa Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 01:59:00 +0200 Subject: [PATCH 30/66] Adds publish/subscribe channels. Unit tests added. --- Makefile | 1 + src/channel.js | 34 +++++++++++++++++++++++++++ test/index.html | 2 ++ test/unit/channel.js | 56 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 src/channel.js create mode 100644 test/unit/channel.js diff --git a/Makefile b/Makefile index 3bb56e3d..a21a7f38 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ ${SRC_DIR}/callbacks.js\ + ${SRC_DIR}/channel.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/channel.js b/src/channel.js new file mode 100644 index 00000000..013b65f1 --- /dev/null +++ b/src/channel.js @@ -0,0 +1,34 @@ +(function( jQuery ) { + + var channels = {}, + channelMethods = { + publish: "fire", + subscribe: "add", + unsubscribe: "remove" + }; + + jQuery.Channel = function( name ) { + var callbacks, + method, + channel = name && channels[ name ]; + if ( !channel ) { + callbacks = jQuery.Callbacks(); + channel = {}; + for ( method in channelMethods ) { + channel[ method ] = callbacks[ channelMethods[ method ] ]; + } + if ( name ) { + channels[ name ] = channel; + } + } + return channel; + }; + + jQuery.each( channelMethods, function( method ) { + jQuery[ method ] = function( name ) { + var channel = jQuery.Channel( name ); + channel[ method ].apply( channel, Array.prototype.slice.call( arguments, 1 ) ); + }; + }); + +})( jQuery ); diff --git a/test/index.html b/test/index.html index bb563846..86b21821 100644 --- a/test/index.html +++ b/test/index.html @@ -10,6 +10,7 @@ + @@ -36,6 +37,7 @@ + diff --git a/test/unit/channel.js b/test/unit/channel.js new file mode 100644 index 00000000..ca8fcbd3 --- /dev/null +++ b/test/unit/channel.js @@ -0,0 +1,56 @@ +module("channel", { teardown: moduleTeardown }); + +test( "jQuery.Channel - Anonymous Channel", function() { + + expect( 4 ); + + var channel = jQuery.Channel(), + count = 0; + + function firstCallback( value ) { + strictEqual( count, 1, "Callback called when needed" ); + strictEqual( value, "test", "Published value received" ); + } + + count++; + channel.subscribe( firstCallback ); + channel.publish( "test" ); + channel.unsubscribe( firstCallback ); + count++; + channel.subscribe(function( value ) { + strictEqual( count, 2, "Callback called when needed" ); + strictEqual( value, "test", "Published value received" ); + }); + channel.publish( "test" ); + +}); + +test( "jQuery.Channel - Named Channel", function() { + + expect( 2 ); + + function callback( value ) { + ok( true, "Callback called" ); + strictEqual( value, "test", "Proper value received" ); + } + + jQuery.Channel( "test" ).subscribe( callback ); + jQuery.Channel( "test" ).publish( "test" ); + jQuery.Channel( "test" ).unsubscribe( callback ); + jQuery.Channel( "test" ).publish( "test" ); +}); + +test( "jQuery.Channel - Helpers", function() { + + expect( 2 ); + + function callback( value ) { + ok( true, "Callback called" ); + strictEqual( value, "test", "Proper value received" ); + } + + jQuery.subscribe( "test", callback ); + jQuery.publish( "test" , "test" ); + jQuery.unsubscribe( "test", callback ); + jQuery.publish( "test" , "test" ); +}); From 1f084d024dc2476eef227cb83460672091780792 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 17:27:05 +0200 Subject: [PATCH 31/66] Shortens slice expression in channel helpers as per rwaldron's suggestion. --- src/channel.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/channel.js b/src/channel.js index 013b65f1..66b2745a 100644 --- a/src/channel.js +++ b/src/channel.js @@ -5,7 +5,8 @@ publish: "fire", subscribe: "add", unsubscribe: "remove" - }; + }, + sliceChannel = [].slice; jQuery.Channel = function( name ) { var callbacks, @@ -27,7 +28,7 @@ jQuery.each( channelMethods, function( method ) { jQuery[ method ] = function( name ) { var channel = jQuery.Channel( name ); - channel[ method ].apply( channel, Array.prototype.slice.call( arguments, 1 ) ); + channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) ); }; }); From 13c330a0f8cd9f1dd9524ccede2668c859cdfab0 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:16:51 +0200 Subject: [PATCH 32/66] $.Callbacks.remove now accepts multiple parameters (Unit test amended). Changed the variable name of the main object from "object" to "self" as per rwaldron's suggestions. --- src/callbacks.js | 57 ++++++++++++++++++++++++------------------ test/unit/callbacks.js | 8 +++--- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/src/callbacks.js b/src/callbacks.js index b3635df7..8be35094 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -70,7 +70,7 @@ jQuery.Callbacks = function( flags, filter ) { firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, - // Add a list of callbacks to the list + // Add one or several callbacks to the list add = function( args ) { var i, length, @@ -87,9 +87,9 @@ jQuery.Callbacks = function( flags, filter ) { // If we have to relocate, we remove the callback // if it already exists if ( flags.relocate ) { - object.remove( elem ); + self.remove( elem ); // Skip if we're in unique mode and callback is already in - } else if ( flags.unique && object.has( elem ) ) { + } else if ( flags.unique && self.has( elem ) ) { continue; } // Get the filtered function if needs be @@ -100,6 +100,7 @@ jQuery.Callbacks = function( flags, filter ) { } } }, + // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; @@ -118,16 +119,17 @@ jQuery.Callbacks = function( flags, filter ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); - object.fireWith( memory[ 0 ], memory[ 1 ] ); + self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { - object.disable(); + self.disable(); } else { list = []; } } }, - object = { + // Actual Callbacks object + self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { @@ -150,25 +152,30 @@ jQuery.Callbacks = function( flags, filter ) { return this; }, // Remove a callback from the list - remove: function( fn ) { + remove: function() { if ( list ) { - for ( var i = 0; i < list.length; i++ ) { - if ( fn === list[ i ][ 0 ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ][ 0 ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } } } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique || flags.relocate ) { - break; + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique || flags.relocate ) { + break; + } } } } @@ -206,7 +213,7 @@ jQuery.Callbacks = function( flags, filter ) { lock: function() { stack = undefined; if ( !memory || memory === true ) { - object.disable(); + self.disable(); } return this; }, @@ -229,7 +236,7 @@ jQuery.Callbacks = function( flags, filter ) { }, // Call all the callbacks with the given arguments fire: function() { - object.fireWith( this, arguments ); + self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once @@ -238,7 +245,7 @@ jQuery.Callbacks = function( flags, filter ) { } }; - return object; + return self; }; })( jQuery ); diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index f179a6b1..54817de4 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -98,12 +98,10 @@ jQuery.each( tests, function( flags, resultString ) { // Basic binding, removing and firing output = "X"; cblist = jQuery.Callbacks( flags ); - cblist.add( outputA ); - cblist.add( outputB ); - cblist.add( outputC ); - cblist.remove( outputB ); + cblist.add( outputA, outputB, outputC ); + cblist.remove( outputB, outputC ); cblist.fire(); - strictEqual( output, "XAC", "Basic binding, removing and firing" ); + strictEqual( output, "XA", "Basic binding, removing and firing" ); // Empty output = "X"; From b136d9cc7aecd8db245b178fc1650e5e5d773172 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:18:08 +0200 Subject: [PATCH 33/66] jQuery.subscribe now returns a handle that can be passed to jQuery.unsubscribe to... well... unsubscribe. Unit test amended. --- src/channel.js | 38 ++++++++++++++++++++++++-------------- test/unit/channel.js | 14 +++++++++++++- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/channel.js b/src/channel.js index 66b2745a..052c3f8f 100644 --- a/src/channel.js +++ b/src/channel.js @@ -1,11 +1,6 @@ (function( jQuery ) { var channels = {}, - channelMethods = { - publish: "fire", - subscribe: "add", - unsubscribe: "remove" - }, sliceChannel = [].slice; jQuery.Channel = function( name ) { @@ -14,10 +9,11 @@ channel = name && channels[ name ]; if ( !channel ) { callbacks = jQuery.Callbacks(); - channel = {}; - for ( method in channelMethods ) { - channel[ method ] = callbacks[ channelMethods[ method ] ]; - } + channel = { + publish: callbacks.fire, + subscribe: callbacks.add, + unsubscribe: callbacks.remove + }; if ( name ) { channels[ name ] = channel; } @@ -25,11 +21,25 @@ return channel; }; - jQuery.each( channelMethods, function( method ) { - jQuery[ method ] = function( name ) { - var channel = jQuery.Channel( name ); - channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) ); - }; + jQuery.extend({ + subscribe: function( id ) { + var channel = jQuery.Channel( id ), + args = sliceChannel.call( arguments, 1 ); + channel.subscribe.apply( channel, args ); + return { + channel: channel, + args: args + }; + }, + unsubscribe: function( id ) { + var channel = id && id.channel || jQuery.Channel( id ); + channel.unsubscribe.apply( channel, id && id.args || + sliceChannel.call( arguments, 1 ) ); + }, + publish: function( id ) { + var channel = jQuery.Channel( id ); + channel.publish.apply( channel, sliceChannel.call( arguments, 1 ) ); + } }); })( jQuery ); diff --git a/test/unit/channel.js b/test/unit/channel.js index ca8fcbd3..b5e7a726 100644 --- a/test/unit/channel.js +++ b/test/unit/channel.js @@ -42,7 +42,7 @@ test( "jQuery.Channel - Named Channel", function() { test( "jQuery.Channel - Helpers", function() { - expect( 2 ); + expect( 4 ); function callback( value ) { ok( true, "Callback called" ); @@ -53,4 +53,16 @@ test( "jQuery.Channel - Helpers", function() { jQuery.publish( "test" , "test" ); jQuery.unsubscribe( "test", callback ); jQuery.publish( "test" , "test" ); + + + var test = true, + subscription = jQuery.subscribe( "test", function() { + ok( test, "first callback called" ); + }, function() { + ok( test, "second callback called" ); + }); + jQuery.publish( "test" ); + test = false; + jQuery.unsubscribe( subscription ); + jQuery.publish( "test" ); }); From 0c9c9fb3cff41bb5deca0220457819498f40f020 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Tue, 24 May 2011 21:37:38 +0200 Subject: [PATCH 34/66] Renames $.Channel as $.Topic to be on par with usual terminology of existing pub/sub implementations. --- Makefile | 2 +- src/channel.js | 45 ------------------------------ src/topic.js | 45 ++++++++++++++++++++++++++++++ test/index.html | 4 +-- test/unit/{channel.js => topic.js} | 28 +++++++++---------- 5 files changed, 62 insertions(+), 62 deletions(-) delete mode 100644 src/channel.js create mode 100644 src/topic.js rename test/unit/{channel.js => topic.js} (63%) diff --git a/Makefile b/Makefile index a21a7f38..4a0a80ba 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ POST_COMPILER = ${JS_ENGINE} ${BUILD_DIR}/post-compile.js BASE_FILES = ${SRC_DIR}/core.js\ ${SRC_DIR}/callbacks.js\ - ${SRC_DIR}/channel.js\ + ${SRC_DIR}/topic.js\ ${SRC_DIR}/deferred.js\ ${SRC_DIR}/support.js\ ${SRC_DIR}/data.js\ diff --git a/src/channel.js b/src/channel.js deleted file mode 100644 index 052c3f8f..00000000 --- a/src/channel.js +++ /dev/null @@ -1,45 +0,0 @@ -(function( jQuery ) { - - var channels = {}, - sliceChannel = [].slice; - - jQuery.Channel = function( name ) { - var callbacks, - method, - channel = name && channels[ name ]; - if ( !channel ) { - callbacks = jQuery.Callbacks(); - channel = { - publish: callbacks.fire, - subscribe: callbacks.add, - unsubscribe: callbacks.remove - }; - if ( name ) { - channels[ name ] = channel; - } - } - return channel; - }; - - jQuery.extend({ - subscribe: function( id ) { - var channel = jQuery.Channel( id ), - args = sliceChannel.call( arguments, 1 ); - channel.subscribe.apply( channel, args ); - return { - channel: channel, - args: args - }; - }, - unsubscribe: function( id ) { - var channel = id && id.channel || jQuery.Channel( id ); - channel.unsubscribe.apply( channel, id && id.args || - sliceChannel.call( arguments, 1 ) ); - }, - publish: function( id ) { - var channel = jQuery.Channel( id ); - channel.publish.apply( channel, sliceChannel.call( arguments, 1 ) ); - } - }); - -})( jQuery ); diff --git a/src/topic.js b/src/topic.js new file mode 100644 index 00000000..c856db8c --- /dev/null +++ b/src/topic.js @@ -0,0 +1,45 @@ +(function( jQuery ) { + + var topics = {}, + sliceTopic = [].slice; + + jQuery.Topic = function( id ) { + var callbacks, + method, + topic = id && topics[ id ]; + if ( !topic ) { + callbacks = jQuery.Callbacks(); + topic = { + publish: callbacks.fire, + subscribe: callbacks.add, + unsubscribe: callbacks.remove + }; + if ( id ) { + topics[ id ] = topic; + } + } + return topic; + }; + + jQuery.extend({ + subscribe: function( id ) { + var topic = jQuery.Topic( id ), + args = sliceTopic.call( arguments, 1 ); + topic.subscribe.apply( topic, args ); + return { + topic: topic, + args: args + }; + }, + unsubscribe: function( id ) { + var topic = id && id.topic || jQuery.Topic( id ); + topic.unsubscribe.apply( topic, id && id.args || + sliceTopic.call( arguments, 1 ) ); + }, + publish: function( id ) { + var topic = jQuery.Topic( id ); + topic.publish.apply( topic, sliceTopic.call( arguments, 1 ) ); + } + }); + +})( jQuery ); diff --git a/test/index.html b/test/index.html index 86b21821..0314092a 100644 --- a/test/index.html +++ b/test/index.html @@ -10,7 +10,7 @@ - + @@ -37,7 +37,7 @@ - + diff --git a/test/unit/channel.js b/test/unit/topic.js similarity index 63% rename from test/unit/channel.js rename to test/unit/topic.js index b5e7a726..0b126fe3 100644 --- a/test/unit/channel.js +++ b/test/unit/topic.js @@ -1,10 +1,10 @@ -module("channel", { teardown: moduleTeardown }); +module("topic", { teardown: moduleTeardown }); -test( "jQuery.Channel - Anonymous Channel", function() { +test( "jQuery.Topic - Anonymous Topic", function() { expect( 4 ); - var channel = jQuery.Channel(), + var topic = jQuery.Topic(), count = 0; function firstCallback( value ) { @@ -13,19 +13,19 @@ test( "jQuery.Channel - Anonymous Channel", function() { } count++; - channel.subscribe( firstCallback ); - channel.publish( "test" ); - channel.unsubscribe( firstCallback ); + topic.subscribe( firstCallback ); + topic.publish( "test" ); + topic.unsubscribe( firstCallback ); count++; - channel.subscribe(function( value ) { + topic.subscribe(function( value ) { strictEqual( count, 2, "Callback called when needed" ); strictEqual( value, "test", "Published value received" ); }); - channel.publish( "test" ); + topic.publish( "test" ); }); -test( "jQuery.Channel - Named Channel", function() { +test( "jQuery.Topic - Named Topic", function() { expect( 2 ); @@ -34,13 +34,13 @@ test( "jQuery.Channel - Named Channel", function() { strictEqual( value, "test", "Proper value received" ); } - jQuery.Channel( "test" ).subscribe( callback ); - jQuery.Channel( "test" ).publish( "test" ); - jQuery.Channel( "test" ).unsubscribe( callback ); - jQuery.Channel( "test" ).publish( "test" ); + jQuery.Topic( "test" ).subscribe( callback ); + jQuery.Topic( "test" ).publish( "test" ); + jQuery.Topic( "test" ).unsubscribe( callback ); + jQuery.Topic( "test" ).publish( "test" ); }); -test( "jQuery.Channel - Helpers", function() { +test( "jQuery.Topic - Helpers", function() { expect( 4 ); From 950da8ae7f408032a91089a5d5c7befa4cd168aa Mon Sep 17 00:00:00 2001 From: jaubourg Date: Thu, 26 May 2011 18:38:34 +0100 Subject: [PATCH 35/66] Added queue flag to $.Callbacks. Unit tests added (more to come). --- src/callbacks.js | 6 ++++++ test/unit/callbacks.js | 1 + 2 files changed, 7 insertions(+) diff --git a/src/callbacks.js b/src/callbacks.js index 8be35094..a1caf91f 100644 --- a/src/callbacks.js +++ b/src/callbacks.js @@ -34,6 +34,9 @@ function createFlags( flags ) { * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * + * queue: only first callback in the list is called each time the list is fired + * (cannot be used in conjunction with memory) + * * unique: will ensure a callback can only be added once (no duplicate in the list) * * relocate: like "unique" but will relocate the callback at the end of the list @@ -112,6 +115,9 @@ jQuery.Callbacks = function( flags, filter ) { if ( list[ firingIndex ][ 1 ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; + } else if ( flags.queue ) { + list.splice( firingIndex, 1 ); + break; } } firing = false; diff --git a/test/unit/callbacks.js b/test/unit/callbacks.js index 54817de4..fcc3ee46 100644 --- a/test/unit/callbacks.js +++ b/test/unit/callbacks.js @@ -19,6 +19,7 @@ var output, "relocate": "XABC X XAABC X XBB X XBA X", "stopOnFalse": "XABC X XABCABCC X XBB X XA X", "addAfterFire": "XAB X XABCAB X XBB X XABA X", + "queue": "XA X XB X XB X XA X", "once memory": "XABC XABC X XA X XA XABA XC", "once unique": "XABC X X X X X XAB X", "once relocate": "XABC X X X X X XBA X", From 9d0b36145870f7d95008f318e86c82eadf0c1eee Mon Sep 17 00:00:00 2001 From: jaubourg Date: Thu, 26 May 2011 18:50:33 +0100 Subject: [PATCH 36/66] Fixes #9104 again. --- src/deferred.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/deferred.js b/src/deferred.js index 7592e361..e527e938 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -50,7 +50,7 @@ jQuery.extend({ if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); - if ( jQuery.isFunction( returned.promise ) ) { + if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.ping ); } else { newDefer[ action ]( returned ); From 1d202c6afc03c98dc656bf6bbde317fb0d050574 Mon Sep 17 00:00:00 2001 From: timmywil Date: Thu, 26 May 2011 16:51:41 -0400 Subject: [PATCH 37/66] Move the value attrHook to the main attrHooks object to save bytes --- src/attributes.js | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/attributes.js b/src/attributes.js index 5396a90e..abe52b89 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -414,6 +414,25 @@ jQuery.extend({ 0 : undefined; } + }, + // Use the value property for back compat + // Use the formHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( formHook && jQuery.nodeName( elem, "button" ) ) { + return formHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( formHook && jQuery.nodeName( elem, "button" ) ) { + return formHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } } }, @@ -497,26 +516,6 @@ boolHook = { } }; -// Use the value property for back compat -// Use the formHook for button elements in IE6/7 (#1954) -jQuery.attrHooks.value = { - get: function( elem, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( formHook && jQuery.nodeName( elem, "button" ) ) { - return formHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } -}; - // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { From 71d2e657d00e7e6f283503eaac4d06e7e5d77ff9 Mon Sep 17 00:00:00 2001 From: timmywil Date: Mon, 6 Jun 2011 20:15:16 -0400 Subject: [PATCH 38/66] Update QUnit. --- test/qunit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/qunit b/test/qunit index d97b37ec..d4f23f8a 160000 --- a/test/qunit +++ b/test/qunit @@ -1 +1 @@ -Subproject commit d97b37ec322136406790e75d03333559f38bbecb +Subproject commit d4f23f8a882d13b71768503e2db9fa33ef169ba0 From c3c001cf5b0970457cc9d7492cb66bdc9a901a1e Mon Sep 17 00:00:00 2001 From: rwldrn Date: Mon, 6 Jun 2011 20:16:14 -0400 Subject: [PATCH 39/66] Landing pull request 404. Removes unused hasOwn var declaration. Fixes #9510. More Details: - https://github.com/jquery/jquery/pull/404 - http://bugs.jquery.com/ticket/9510 --- src/event.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/event.js b/src/event.js index d2d57d67..3f53ab5c 100644 --- a/src/event.js +++ b/src/event.js @@ -1,7 +1,6 @@ (function( jQuery ) { -var hasOwn = Object.prototype.hasOwnProperty, - rnamespaces = /\.(.*)$/, +var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, From 07420566452622f37b01e69bbbdcbeeb5317e065 Mon Sep 17 00:00:00 2001 From: rwldrn Date: Mon, 6 Jun 2011 20:18:36 -0400 Subject: [PATCH 40/66] Landing pull request 403. Check for both camelized and hyphenated data property names; Fixes #9301. More Details: - https://github.com/jquery/jquery/pull/403 - http://bugs.jquery.com/ticket/9301 --- src/data.js | 5 ++++- test/unit/data.js | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/data.js b/src/data.js index c019a64e..f69d9dec 100644 --- a/src/data.js +++ b/src/data.js @@ -108,7 +108,10 @@ jQuery.extend({ return thisCache[ internalKey ] && thisCache[ internalKey ].events; } - return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache; + return getByName ? + // Check for both converted-to-camel and non-converted data property names + thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] : + thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { diff --git a/test/unit/data.js b/test/unit/data.js index 1af2077e..87a3de33 100644 --- a/test/unit/data.js +++ b/test/unit/data.js @@ -508,3 +508,20 @@ test("jQuery.data should follow html5 specification regarding camel casing", fun div.remove(); }); + +test("jQuery.data should not miss data with preset hyphenated property names", function() { + + expect(2); + + var div = jQuery("
", { id: "hyphened" }).appendTo("#qunit-fixture"), + test = { + "camelBar": "camelBar", + "hyphen-foo": "hyphen-foo" + }; + + div.data( test ); + + jQuery.each( test , function(i, k) { + equal( div.data(k), k, "data with property '"+k+"' was correctly found"); + }); +}); From 80ad14bd14467c547c2867f2677ca581aa29bf33 Mon Sep 17 00:00:00 2001 From: Mike Sherov Date: Mon, 6 Jun 2011 23:13:37 -0400 Subject: [PATCH 41/66] Add margin after checking width. Add tests. Fixes #9441. Fixes #9300. --- src/css.js | 69 ++++++++++++++++++++++++++++------------- test/unit/dimensions.js | 24 ++++++++++++++ 2 files changed, 71 insertions(+), 22 deletions(-) diff --git a/src/css.js b/src/css.js index e3ab270f..47e6f31e 100644 --- a/src/css.js +++ b/src/css.js @@ -168,12 +168,11 @@ jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { - var val; + var val, fellback = false; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); - } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); @@ -188,20 +187,37 @@ jQuery.each(["height", "width"], function( i, name ) { } if ( val != null ) { - // Should return "auto" instead of 0, use 0 for - // temporary backwards-compat - return val === "" || val === "auto" ? "0px" : val; + fellback = true; } } - if ( val < 0 || val == null ) { + if ( !fellback && ( val < 0 || val == null ) ) { val = elem.style[ name ]; - // Should return "auto" instead of 0, use 0 for - // temporary backwards-compat - return val === "" || val === "auto" ? "0px" : val; + fellback = true; } - return typeof val === "string" ? val : val + "px"; + // Should return "auto" instead of 0, use 0 for + // temporary backwards-compat + if ( fellback && ( val === "" || val === "auto" ) ) { + val = "0px"; + } else if ( typeof val !== "string" ) { + val += "px"; + } + + if ( extra ) { + val = parseFloat( val ) || 0; + if ( fellback ) { + val += adjustWH( elem, name, "padding" ); + if ( extra !== "padding" ) { + val += adjustWH( elem, name, "border", "Width" ); + } + } + if ( extra === "margin" ) { + val += adjustWH( elem, name, "margin" ); + } + } + + return val; } }, @@ -331,24 +347,33 @@ if ( document.documentElement.currentStyle ) { curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { - var which = name === "width" ? cssWidth : cssHeight, - val = name === "width" ? elem.offsetWidth : elem.offsetHeight; + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } + if ( !extra ) { + val -= adjustWH( elem, name, "padding"); + } + + if ( extra !== "margin" ) { + val -= adjustWH( elem, name, "border", "Width"); + } + + return val; +} + +function adjustWH( elem, name, prepend, append ) { + var which = name === "width" ? cssWidth : cssHeight, + val = 0; + + if( !append ){ + append = ""; + } + jQuery.each( which, function() { - if ( !extra ) { - val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; - } - - if ( extra === "margin" ) { - val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; - - } else { - val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; - } + val += parseFloat( jQuery.css( elem, prepend + this + append ) ) || 0; }); return val; diff --git a/test/unit/dimensions.js b/test/unit/dimensions.js index 83cc3908..2b063706 100644 --- a/test/unit/dimensions.js +++ b/test/unit/dimensions.js @@ -211,6 +211,30 @@ test("outerWidth()", function() { jQuery.removeData($div[0], "olddisplay", true); }); +test("child of a hidden elem has accurate inner/outer/Width()/Height() see #9441 #9300", function() { + expect(8); + + //setup html + var $divNormal = jQuery( '
' ).css({ width: "100px", border: "10px solid white", padding: "2px", margin: "3px" }); + var $divChild = $divNormal.clone(); + var $divHiddenParent = jQuery( '
' ).css( "display", "none" ).append( $divChild ); + jQuery( 'body' ).append( $divHiddenParent ).append( $divNormal ); + + //tests that child div of a hidden div works the same as a normal div + equals( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" ); + equals( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" ); + equals( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" ); + equals( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" ); + equals( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" ); + equals( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" ); + equals( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" ); + equals( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" ); + + //teardown html + $divHiddenParent.remove(); + $divNormal.remove(); +}); + test("outerHeight()", function() { expect(11); From 75203de7435b7f32c69da1dde88aa6708bf6bb7d Mon Sep 17 00:00:00 2001 From: timmywil Date: Mon, 6 Jun 2011 23:35:16 -0400 Subject: [PATCH 42/66] Optimize width/height retrieval (moved logic to getWH, removed adjustWH). Supplements #9441, #9300. --- src/css.js | 103 ++++++++++++++++------------------------ src/dimensions.js | 6 +-- test/unit/dimensions.js | 15 +++--- 3 files changed, 51 insertions(+), 73 deletions(-) diff --git a/src/css.js b/src/css.js index 47e6f31e..cc249ce7 100644 --- a/src/css.js +++ b/src/css.js @@ -172,51 +172,13 @@ jQuery.each(["height", "width"], function( i, name ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { - val = getWH( elem, name, extra ); + return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } - if ( val <= 0 ) { - val = curCSS( elem, name, name ); - - if ( val === "0px" && currentStyle ) { - val = currentStyle( elem, name, name ); - } - - if ( val != null ) { - fellback = true; - } - } - - if ( !fellback && ( val < 0 || val == null ) ) { - val = elem.style[ name ]; - fellback = true; - } - - // Should return "auto" instead of 0, use 0 for - // temporary backwards-compat - if ( fellback && ( val === "" || val === "auto" ) ) { - val = "0px"; - } else if ( typeof val !== "string" ) { - val += "px"; - } - - if ( extra ) { - val = parseFloat( val ) || 0; - if ( fellback ) { - val += adjustWH( elem, name, "padding" ); - if ( extra !== "padding" ) { - val += adjustWH( elem, name, "border", "Width" ); - } - } - if ( extra === "margin" ) { - val += adjustWH( elem, name, "margin" ); - } - } - return val; } }, @@ -224,7 +186,7 @@ jQuery.each(["height", "width"], function( i, name ) { set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 - value = parseFloat(value); + value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; @@ -347,36 +309,51 @@ if ( document.documentElement.currentStyle ) { curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { - var val = name === "width" ? elem.offsetWidth : elem.offsetHeight; - if ( extra === "border" ) { - return val; + // Start with offset property + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + which = name === "width" ? cssWidth : cssHeight; + + if ( extra !== "margin" && extra !== "border" ) { + jQuery.each( which, function() { + val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; + if ( !extra ) { + val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; + } + }); } - if ( !extra ) { - val -= adjustWH( elem, name, "padding"); + if ( val > 0 ) { + if ( extra === "margin" ) { + jQuery.each( which, function() { + val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; + }); + } + return val + "px"; } - if ( extra !== "margin" ) { - val -= adjustWH( elem, name, "border", "Width"); + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, name ); + if ( val < 0 || val == null ) { + val = elem.style[ name ] || 0; + } + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + + // Add padding, border, margin + if ( extra ) { + jQuery.each( which, function() { + val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; + if ( extra !== "padding" ) { + val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; + } + if ( extra === "margin" ) { + val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; + } + }); } - return val; -} - -function adjustWH( elem, name, prepend, append ) { - var which = name === "width" ? cssWidth : cssHeight, - val = 0; - - if( !append ){ - append = ""; - } - - jQuery.each( which, function() { - val += parseFloat( jQuery.css( elem, prepend + this + append ) ) || 0; - }); - - return val; + return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { diff --git a/src/dimensions.js b/src/dimensions.js index 8559056b..88fa1750 100644 --- a/src/dimensions.js +++ b/src/dimensions.js @@ -1,12 +1,12 @@ (function( jQuery ) { -// Create innerHeight, innerWidth, outerHeight and outerWidth methods +// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth - jQuery.fn["inner" + name] = function() { + jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : @@ -14,7 +14,7 @@ jQuery.each([ "Height", "Width" ], function( i, name ) { }; // outerHeight and outerWidth - jQuery.fn["outer" + name] = function( margin ) { + jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : diff --git a/test/unit/dimensions.js b/test/unit/dimensions.js index 2b063706..57229199 100644 --- a/test/unit/dimensions.js +++ b/test/unit/dimensions.js @@ -214,23 +214,24 @@ test("outerWidth()", function() { test("child of a hidden elem has accurate inner/outer/Width()/Height() see #9441 #9300", function() { expect(8); - //setup html - var $divNormal = jQuery( '
' ).css({ width: "100px", border: "10px solid white", padding: "2px", margin: "3px" }); - var $divChild = $divNormal.clone(); - var $divHiddenParent = jQuery( '
' ).css( "display", "none" ).append( $divChild ); - jQuery( 'body' ).append( $divHiddenParent ).append( $divNormal ); + // setup html + var $divNormal = jQuery("
").css({ width: "100px", height: "100px", border: "10px solid white", padding: "2px", margin: "3px" }), + $divChild = $divNormal.clone(), + $divHiddenParent = jQuery("
").css( "display", "none" ).append( $divChild ).appendTo("body"); + $divNormal.appendTo("body"); - //tests that child div of a hidden div works the same as a normal div + // tests that child div of a hidden div works the same as a normal div equals( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" ); equals( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" ); equals( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" ); equals( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" ); + equals( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" ); equals( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" ); equals( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" ); equals( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" ); - //teardown html + // teardown html $divHiddenParent.remove(); $divNormal.remove(); }); From 6490c10c751af6ad8cd119526db227939cdcffe9 Mon Sep 17 00:00:00 2001 From: rwldrn Date: Mon, 6 Jun 2011 23:54:17 -0400 Subject: [PATCH 43/66] Landing pull request 401. Nulling all elements created in support.js; Fixes #9471. More Details: - https://github.com/jquery/jquery/pull/401 - http://bugs.jquery.com/ticket/9471 --- src/support.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/support.js b/src/support.js index 42108ded..882b84a2 100644 --- a/src/support.js +++ b/src/support.js @@ -245,7 +245,7 @@ jQuery.support = (function() { } // Null connected elements to avoid leaks in IE - marginDiv = div = input = null; + testElement = fragment = select = opt = body = marginDiv = div = input = null; return support; })(); From d66c3b6d84c2af1132727c5be335bc2860dcbda9 Mon Sep 17 00:00:00 2001 From: timmywil Date: Tue, 7 Jun 2011 00:04:17 -0400 Subject: [PATCH 44/66] Remove fellback in width/height cssHook --- src/css.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/css.js b/src/css.js index cc249ce7..fcc784d2 100644 --- a/src/css.js +++ b/src/css.js @@ -168,7 +168,7 @@ jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { - var val, fellback = false; + var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { From 0a80be67f4fe968d99777564a02aeddbde1fbf35 Mon Sep 17 00:00:00 2001 From: timmywil Date: Mon, 6 Jun 2011 20:13:50 -0400 Subject: [PATCH 45/66] Add catch block to try/finally in deferred. Fixes #9033. Test case needed. --- src/deferred.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/deferred.js b/src/deferred.js index 5cc5fb5b..3d53344e 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -58,8 +58,9 @@ jQuery.extend({ while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } - } - finally { + } catch( e ) { + throw e; + } finally { fired = [ context, args ]; firing = 0; } From db437be6e31c924aade13bb719f9facc122b3d9c Mon Sep 17 00:00:00 2001 From: timmywil Date: Tue, 7 Jun 2011 20:54:11 -0400 Subject: [PATCH 46/66] Check classes passed for duplicates. Fixes #9499. --- src/attributes.js | 47 ++++++++++++++++++++++------------------- src/effects.js | 4 ++-- test/data/testsuite.css | 2 +- test/unit/attributes.js | 13 ++++++++++-- 4 files changed, 39 insertions(+), 27 deletions(-) diff --git a/src/attributes.js b/src/attributes.js index abe52b89..5b68773c 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -37,30 +37,31 @@ jQuery.fn.extend({ }, addClass: function( value ) { + var classNames, i, l, elem, setClass, c, cl; + if ( jQuery.isFunction( value ) ) { - return this.each(function(i) { - var self = jQuery(this); - self.addClass( value.call(this, i, self.attr("class") || "") ); + return this.each(function( j ) { + var self = jQuery( this ); + self.addClass( value.call(this, j, self.attr("class") || "") ); }); } if ( value && typeof value === "string" ) { - var classNames = (value || "").split( rspace ); + classNames = value.split( rspace ); - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; if ( elem.nodeType === 1 ) { - if ( !elem.className ) { + if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { - var className = " " + elem.className + " ", - setClass = elem.className; + setClass = elem.className; - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { - setClass += " " + classNames[c]; + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf(classNames[ c ]) ) { + setClass += " " + classNames[ c ]; } } elem.className = jQuery.trim( setClass ); @@ -73,24 +74,26 @@ jQuery.fn.extend({ }, removeClass: function( value ) { - if ( jQuery.isFunction(value) ) { - return this.each(function(i) { - var self = jQuery(this); - self.removeClass( value.call(this, i, self.attr("class")) ); + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + var self = jQuery( this ); + self.removeClass( value.call(this, j, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { - var classNames = (value || "").split( rspace ); + classNames = (value || "").split( rspace ); - for ( var i = 0, l = this.length; i < l; i++ ) { - var elem = this[i]; + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { - var className = (" " + elem.className + " ").replace(rclass, " "); - for ( var c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[c] + " ", " "); + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); diff --git a/src/effects.js b/src/effects.js index 22496277..3a4e2663 100644 --- a/src/effects.js +++ b/src/effects.js @@ -15,8 +15,8 @@ var elemdisplay = {}, ], fxNow, requestAnimationFrame = window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - window.oRequestAnimationFrame; + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame; jQuery.fn.extend({ show: function( speed, easing, callback ) { diff --git a/test/data/testsuite.css b/test/data/testsuite.css index 47caf34a..295740f5 100644 --- a/test/data/testsuite.css +++ b/test/data/testsuite.css @@ -119,5 +119,5 @@ sup { display: none; } dfn { display: none; } /* #9239 Attach a background to the body( avoid crashes in removing the test element in support ) */ -body, div { background: url(http://www.ctemploymentlawblog.com/test.jpg) no-repeat -1000px 0; } +body, div { background: url(http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif) no-repeat -1000px 0; } diff --git a/test/unit/attributes.js b/test/unit/attributes.js index 56c398e5..37260f2f 100644 --- a/test/unit/attributes.js +++ b/test/unit/attributes.js @@ -761,12 +761,14 @@ test("val(select) after form.reset() (Bug #2551)", function() { }); var testAddClass = function(valueObj) { - expect(5); + expect(7); var div = jQuery("div"); div.addClass( valueObj("test") ); var pass = true; for ( var i = 0; i < div.size(); i++ ) { - if ( div.get(i).className.indexOf("test") == -1 ) pass = false; + if ( !~div.get(i).className.indexOf("test") ) { + pass = false; + } } ok( pass, "Add Class" ); @@ -787,6 +789,13 @@ var testAddClass = function(valueObj) { div.attr("class", "foo"); div.addClass( valueObj("bar baz") ); equals( div.attr("class"), "foo bar baz", "Make sure there isn't too much trimming." ); + + div.removeAttr("class"); + div.addClass( valueObj("foo") ).addClass( valueObj("foo") ) + equal( div.attr("class"), "foo", "Do not add the same class twice in separate calls." ); + div.removeAttr("class"); + div.addClass( valueObj("bar bar") ); + equal( div.attr("class"), "bar", "Do not add the same class twice in the same call." ); }; test("addClass(String)", function() { From 39a2f29c29fdb296bb178b3c55d805ea0dc2f0ce Mon Sep 17 00:00:00 2001 From: timmywil Date: Wed, 8 Jun 2011 10:55:52 -0400 Subject: [PATCH 47/66] Revert "Add catch block to try/finally in deferred. Fixes #9033. Test case needed." Line of exception was lost when debugging. This reverts commit 0a80be67f4fe968d99777564a02aeddbde1fbf35. --- src/deferred.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/deferred.js b/src/deferred.js index 3d53344e..5cc5fb5b 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -58,9 +58,8 @@ jQuery.extend({ while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } - } catch( e ) { - throw e; - } finally { + } + finally { fired = [ context, args ]; firing = 0; } From 641ad802111d2dc16ccf4b3721784a6addaf20df Mon Sep 17 00:00:00 2001 From: timmywil Date: Mon, 13 Jun 2011 10:02:13 -0400 Subject: [PATCH 48/66] Attribute hooks do not need to be attached in XML docs. Fixes #9568. --- src/attributes.js | 31 +++++++++++++++++-------------- test/data/dashboard.xml | 2 +- test/unit/attributes.js | 7 ++++--- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/attributes.js b/src/attributes.js index 5b68773c..ce7b3502 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -320,21 +320,23 @@ jQuery.extend({ notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed - name = notxml && jQuery.attrFix[ name ] || name; + if ( notxml ) { + name = jQuery.attrFix[ name ] || name; - hooks = jQuery.attrHooks[ name ]; + hooks = jQuery.attrHooks[ name ]; - if ( !hooks ) { - // Use boolHook for boolean attributes - if ( rboolean.test( name ) ) { + if ( !hooks ) { + // Use boolHook for boolean attributes + if ( rboolean.test( name ) ) { - hooks = boolHook; + hooks = boolHook; - // Use formHook for forms and if the name contains certain characters - } else if ( formHook && name !== "className" && - (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { + // Use formHook for forms and if the name contains certain characters + } else if ( formHook && name !== "className" && + (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { - hooks = formHook; + hooks = formHook; + } } } @@ -465,10 +467,11 @@ jQuery.extend({ var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - // Try to normalize/fix the name - name = notxml && jQuery.propFix[ name ] || name; - - hooks = jQuery.propHooks[ name ]; + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { diff --git a/test/data/dashboard.xml b/test/data/dashboard.xml index 10f6b334..5a6f5614 100644 --- a/test/data/dashboard.xml +++ b/test/data/dashboard.xml @@ -1,7 +1,7 @@ - + diff --git a/test/unit/attributes.js b/test/unit/attributes.js index 37260f2f..831f729c 100644 --- a/test/unit/attributes.js +++ b/test/unit/attributes.js @@ -132,11 +132,12 @@ test("attr(String)", function() { if ( !isLocal ) { test("attr(String) in XML Files", function() { - expect(2); + expect(3); stop(); jQuery.get("data/dashboard.xml", function( xml ) { - equals( jQuery( "locations", xml ).attr("class"), "foo", "Check class attribute in XML document" ); - equals( jQuery( "location", xml ).attr("for"), "bar", "Check for attribute in XML document" ); + equal( jQuery( "locations", xml ).attr("class"), "foo", "Check class attribute in XML document" ); + equal( jQuery( "location", xml ).attr("for"), "bar", "Check for attribute in XML document" ); + equal( jQuery( "location", xml ).attr("checked"), "different", "Check that hooks are not attached in XML document" ); start(); }); }); From 6926247bf441deaa0441872849bb3786c257a4cf Mon Sep 17 00:00:00 2001 From: rwldrn Date: Tue, 14 Jun 2011 15:38:46 -0400 Subject: [PATCH 49/66] Landing pull request 397. withinElement rewrite in event. Fixes #6234, #9357, #9447. More Details: - https://github.com/jquery/jquery/pull/397 - http://bugs.jquery.com/ticket/6234 - http://bugs.jquery.com/ticket/9357 - http://bugs.jquery.com/ticket/9447 --- src/event.js | 31 ++++++++++++------------------- test/unit/event.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 19 deletions(-) diff --git a/src/event.js b/src/event.js index 3f53ab5c..131739b1 100644 --- a/src/event.js +++ b/src/event.js @@ -650,34 +650,27 @@ jQuery.Event.prototype = { // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { - // Check if mouse(over|out) are still within the same parent element - var parent = event.relatedTarget; - // set the correct event type + // Check if mouse(over|out) are still within the same parent element + var related = event.relatedTarget, + inside = false, + eventType = event.type; + event.type = event.data; - // Firefox sometimes assigns relatedTarget a XUL element - // which we cannot access the parentNode property of - try { + if ( related !== this ) { - // Chrome does something similar, the parentNode property - // can be accessed but is null. - if ( parent && parent !== document && !parent.parentNode ) { - return; + if ( related ) { + inside = jQuery.contains( this, related ); } - // Traverse up the tree - while ( parent && parent !== this ) { - parent = parent.parentNode; - } + if ( !inside ) { - if ( parent !== this ) { - // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); - } - // assuming we've left the element since we most likely mousedover a xul element - } catch(e) { } + event.type = eventType; + } + } }, // In case of event delegation, we only need to rename the event.type, diff --git a/test/unit/event.js b/test/unit/event.js index f71c7b29..7c628880 100644 --- a/test/unit/event.js +++ b/test/unit/event.js @@ -780,6 +780,43 @@ test("mouseover triggers mouseenter", function() { elem.remove(); }); +test("withinElement implemented with jQuery.contains()", function() { + + expect(1); + + jQuery("#qunit-fixture").append('
'); + + jQuery("#jc-outer").bind("mouseenter mouseleave", function( event ) { + + equal( this.id, "jc-outer", this.id + " " + event.type ); + + }).trigger("mouseenter"); + + jQuery("#jc-inner").trigger("mousenter"); + + jQuery("#jc-outer").unbind("mouseenter mouseleave").remove(); + jQuery("#jc-inner").remove(); + +}); + +test("mouseenter, mouseleave don't catch exceptions", function() { + expect(2); + + var elem = jQuery("#firstp").hover(function() { throw "an Exception"; }); + + try { + elem.mouseenter(); + } catch (e) { + equals( e, "an Exception", "mouseenter doesn't catch exceptions" ); + } + + try { + elem.mouseleave(); + } catch (e) { + equals( e, "an Exception", "mouseleave doesn't catch exceptions" ); + } +}); + test("trigger() shortcuts", function() { expect(6); From 13ceb0f56b380b395ed5a26b468bf2bf00d88216 Mon Sep 17 00:00:00 2001 From: Greg Hazel Date: Tue, 14 Jun 2011 15:51:03 -0400 Subject: [PATCH 50/66] Landing pull request 410. Moves jQuery attachment comment to outro. More Details: - https://github.com/jquery/jquery/pull/410 --- src/core.js | 1 - src/outro.js | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core.js b/src/core.js index 3a32d6f0..2c27bf7c 100644 --- a/src/core.js +++ b/src/core.js @@ -923,7 +923,6 @@ function doScrollCheck() { jQuery.ready(); } -// Expose jQuery to the global object return jQuery; })(); diff --git a/src/outro.js b/src/outro.js index 32b0d087..b49305e7 100644 --- a/src/outro.js +++ b/src/outro.js @@ -1,2 +1,3 @@ +// Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); From 5eef5917fdb399ace2698154c4cd7bbd24f13182 Mon Sep 17 00:00:00 2001 From: rwldrn Date: Tue, 14 Jun 2011 15:59:22 -0400 Subject: [PATCH 51/66] Landing pull request 409. Adds fillOpacity to internal cssNumber. Fixes #9548. More Details: - https://github.com/jquery/jquery/pull/409 - http://bugs.jquery.com/ticket/9548 --- src/css.js | 9 +++++---- test/unit/css.js | 10 ++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/css.js b/src/css.js index fcc784d2..c60bcdde 100644 --- a/src/css.js +++ b/src/css.js @@ -50,13 +50,14 @@ jQuery.extend({ // Exclude the following css properties to add px cssNumber: { - "zIndex": true, + "fillOpacity": true, "fontWeight": true, - "opacity": true, - "zoom": true, "lineHeight": true, + "opacity": true, + "orphans": true, "widows": true, - "orphans": true + "zIndex": true, + "zoom": true }, // Add in properties whose names you wish to fix before diff --git a/test/unit/css.js b/test/unit/css.js index e631f496..f421f7bd 100644 --- a/test/unit/css.js +++ b/test/unit/css.js @@ -475,3 +475,13 @@ test("widows & orphans #8936", function () { $p.remove(); }); + +test("Do not append px to 'fill-opacity' #9548", 1, function() { + + var $div = jQuery("
").appendTo("#qunit-fixture"); + + $div.css("fill-opacity", 0).animate({ "fill-opacity": 1.0 }, 0, function () { + equal( jQuery(this).css("fill-opacity"), 1, "Do not append px to 'fill-opacity'"); + }); + +}); From 8a532d15757f8c3ba491ae14d024e353de6b4c7f Mon Sep 17 00:00:00 2001 From: Schalk Neethling Date: Tue, 14 Jun 2011 16:01:50 -0400 Subject: [PATCH 52/66] Landing pull request 378. Comment typo in core.js. More Details: - https://github.com/jquery/jquery/pull/378 --- src/core.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core.js b/src/core.js index 2c27bf7c..ab0d9f7b 100644 --- a/src/core.js +++ b/src/core.js @@ -792,7 +792,7 @@ jQuery.extend({ }, // Mutifunctional method to get and set values to a collection - // The value/s can be optionally by executed if its a function + // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; From d443e533aa83e89e6a1b02280dfc77f741cb4db6 Mon Sep 17 00:00:00 2001 From: John Resig Date: Tue, 14 Jun 2011 14:54:23 -0700 Subject: [PATCH 53/66] Tagging the 1.6.2rc1 release. --- build/release-notes.js | 4 ++-- test/qunit | 2 +- version.txt | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build/release-notes.js b/build/release-notes.js index 0166732e..57d03789 100644 --- a/build/release-notes.js +++ b/build/release-notes.js @@ -9,8 +9,8 @@ var fs = require("fs"), extract = /(.*?)<[^"]+"component">\s*(\S+)/g; var opts = { - version: "1.6.1 RC 1", - short_version: "1.6rc1", + version: "1.6.1", + short_version: "1.6.1", final_version: "1.6.1", categories: [] }; diff --git a/test/qunit b/test/qunit index d4f23f8a..d97b37ec 160000 --- a/test/qunit +++ b/test/qunit @@ -1 +1 @@ -Subproject commit d4f23f8a882d13b71768503e2db9fa33ef169ba0 +Subproject commit d97b37ec322136406790e75d03333559f38bbecb diff --git a/version.txt b/version.txt index 22e67ce2..a0de7ec1 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.6.2pre \ No newline at end of file +1.6.2rc1 \ No newline at end of file From 138d5b7b811845950279f5ee5391339d7d31e360 Mon Sep 17 00:00:00 2001 From: John Resig Date: Tue, 14 Jun 2011 14:55:14 -0700 Subject: [PATCH 54/66] Updating the source version to 1.6.2pre --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index a0de7ec1..22e67ce2 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.6.2rc1 \ No newline at end of file +1.6.2pre \ No newline at end of file From d269e426e0844fa025e8ca5510c56860a9cde784 Mon Sep 17 00:00:00 2001 From: John Resig Date: Tue, 14 Jun 2011 15:05:27 -0700 Subject: [PATCH 55/66] Updating version in release notes script. --- build/release-notes.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build/release-notes.js b/build/release-notes.js index 57d03789..b112d998 100644 --- a/build/release-notes.js +++ b/build/release-notes.js @@ -9,9 +9,9 @@ var fs = require("fs"), extract = /(.*?)<[^"]+"component">\s*(\S+)/g; var opts = { - version: "1.6.1", - short_version: "1.6.1", - final_version: "1.6.1", + version: "1.6.2 RC 1", + short_version: "1.6.2rc1", + final_version: "1.6.2", categories: [] }; From d59b0f3e27827d189b8b2595142ec6bbc3941dd9 Mon Sep 17 00:00:00 2001 From: John Resig Date: Tue, 14 Jun 2011 15:06:28 -0700 Subject: [PATCH 56/66] Re-updating QUnit, oops. --- test/qunit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/qunit b/test/qunit index d97b37ec..d4f23f8a 160000 --- a/test/qunit +++ b/test/qunit @@ -1 +1 @@ -Subproject commit d97b37ec322136406790e75d03333559f38bbecb +Subproject commit d4f23f8a882d13b71768503e2db9fa33ef169ba0 From 124817e6684086ccf74e509309b73d4b4dd89932 Mon Sep 17 00:00:00 2001 From: Mike Sherov Date: Fri, 17 Jun 2011 17:33:29 -0400 Subject: [PATCH 57/66] Landing pull request 413. Move border/padding checks to after width validation to avoid unnecessary fallbacks. Fixes #9598. More Details: - https://github.com/jquery/jquery/pull/413 - http://bugs.jquery.com/ticket/9300 - http://bugs.jquery.com/ticket/9441 - http://bugs.jquery.com/ticket/9598 --- src/css.js | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/css.js b/src/css.js index c60bcdde..cb7df9f8 100644 --- a/src/css.js +++ b/src/css.js @@ -315,21 +315,20 @@ function getWH( elem, name, extra ) { var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight; - if ( extra !== "margin" && extra !== "border" ) { - jQuery.each( which, function() { - val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; - if ( !extra ) { - val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; - } - }); - } - if ( val > 0 ) { - if ( extra === "margin" ) { + if ( extra !== "border" ) { jQuery.each( which, function() { - val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; + if ( !extra ) { + val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; + } + if ( extra === "margin" ) { + val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; + } else { + val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; + } }); } + return val + "px"; } From 96501d38a935187461d45c40f17f8327b2e7cd91 Mon Sep 17 00:00:00 2001 From: timmywil Date: Sun, 19 Jun 2011 18:58:47 -0400 Subject: [PATCH 58/66] Allow similarly named classes (regression from 9499) and switch class retrieval to property when passing class to value functions. Fixes #9617. --- src/attributes.js | 20 +++++++++----------- test/unit/attributes.js | 15 +++++++++++---- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/attributes.js b/src/attributes.js index ce7b3502..1e0e79f4 100644 --- a/src/attributes.js +++ b/src/attributes.js @@ -37,12 +37,12 @@ jQuery.fn.extend({ }, addClass: function( value ) { - var classNames, i, l, elem, setClass, c, cl; + var classNames, i, l, elem, + setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { - var self = jQuery( this ); - self.addClass( value.call(this, j, self.attr("class") || "") ); + jQuery( this ).addClass( value.call(this, j, this.className) ); }); } @@ -57,11 +57,11 @@ jQuery.fn.extend({ elem.className = value; } else { - setClass = elem.className; + setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf(classNames[ c ]) ) { - setClass += " " + classNames[ c ]; + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); @@ -78,8 +78,7 @@ jQuery.fn.extend({ if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { - var self = jQuery( this ); - self.removeClass( value.call(this, j, self.attr("class")) ); + jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } @@ -112,9 +111,8 @@ jQuery.fn.extend({ isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { - return this.each(function(i) { - var self = jQuery(this); - self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } diff --git a/test/unit/attributes.js b/test/unit/attributes.js index 831f729c..4716e5b5 100644 --- a/test/unit/attributes.js +++ b/test/unit/attributes.js @@ -762,7 +762,8 @@ test("val(select) after form.reset() (Bug #2551)", function() { }); var testAddClass = function(valueObj) { - expect(7); + expect(9); + var div = jQuery("div"); div.addClass( valueObj("test") ); var pass = true; @@ -791,10 +792,16 @@ var testAddClass = function(valueObj) { div.addClass( valueObj("bar baz") ); equals( div.attr("class"), "foo bar baz", "Make sure there isn't too much trimming." ); - div.removeAttr("class"); + div.removeClass(); div.addClass( valueObj("foo") ).addClass( valueObj("foo") ) equal( div.attr("class"), "foo", "Do not add the same class twice in separate calls." ); - div.removeAttr("class"); + + div.addClass( valueObj("fo") ); + equal( div.attr("class"), "foo fo", "Adding a similar class does not get interrupted." ); + div.removeClass().addClass("wrap2"); + ok( div.addClass("wrap").hasClass("wrap"), "Can add similarly named classes"); + + div.removeClass(); div.addClass( valueObj("bar bar") ); equal( div.attr("class"), "bar", "Do not add the same class twice in the same call." ); }; @@ -959,7 +966,7 @@ test("toggleClass(Function[, boolean])", function() { test("toggleClass(Fucntion[, boolean]) with incoming value", function() { expect(14); - var e = jQuery("#firstp"), old = e.attr("class"); + var e = jQuery("#firstp"), old = e.attr("class") || ""; ok( !e.is(".test"), "Assert class not present" ); e.toggleClass(function(i, val) { From ab1504f14f56944a5a6297c68b323f0af01d5be8 Mon Sep 17 00:00:00 2001 From: timmywil Date: Tue, 28 Jun 2011 11:46:03 -0400 Subject: [PATCH 59/66] Set timerId to true instead of a number so that intervals set to 1 are not accidentally cleared when stopped. Fixes #9678. - Adding a working test case would not be possible in this case, but all tests pass. --- src/effects.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/effects.js b/src/effects.js index 3a4e2663..a7529a0f 100644 --- a/src/effects.js +++ b/src/effects.js @@ -411,7 +411,7 @@ jQuery.fx.prototype = { if ( t() && jQuery.timers.push(t) && !timerId ) { // Use requestAnimationFrame instead of setInterval if available if ( requestAnimationFrame ) { - timerId = 1; + timerId = true; raf = function() { // When timerId gets set to null at any point, this stops if ( timerId ) { From aa6f8c8cd399d50e91dc0a3634395b6ebf54b209 Mon Sep 17 00:00:00 2001 From: John Resig Date: Thu, 30 Jun 2011 14:16:56 -0400 Subject: [PATCH 60/66] Tagging the 1.6.2 release. --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index 22e67ce2..308b6faa 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.6.2pre \ No newline at end of file +1.6.2 \ No newline at end of file From e2ab2ba1d51b47f90fd8022e500ea3df563e7d74 Mon Sep 17 00:00:00 2001 From: John Resig Date: Thu, 30 Jun 2011 14:17:44 -0400 Subject: [PATCH 61/66] Updating the source version to 1.6.3pre --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index 308b6faa..e37c079f 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.6.2 \ No newline at end of file +1.6.3pre \ No newline at end of file From 5b92a5f5eccf69d480c11dbd2870f8161ae0441b Mon Sep 17 00:00:00 2001 From: jaubourg Date: Thu, 30 Jun 2011 18:18:44 +0200 Subject: [PATCH 62/66] Replaces typo (status instead of state) as observed in #9585. --- src/ajax.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ajax.js b/src/ajax.js index a16717b0..e4e48dc7 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -727,7 +727,7 @@ jQuery.extend({ transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done - if ( status < 2 ) { + if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { From 139135a98aab1c422e5ae05b026535a40d58328f Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 1 Jul 2011 01:51:50 +0200 Subject: [PATCH 63/66] Fixes #9446. Context is properly propagated using pipe. If context was the original deferred, then context is updated to next deferred in the chain. Unit tests added. --- src/deferred.js | 2 +- test/unit/deferred.js | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/deferred.js b/src/deferred.js index 5cc5fb5b..e543f151 100644 --- a/src/deferred.js +++ b/src/deferred.js @@ -122,7 +122,7 @@ jQuery.extend({ if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { - newDefer[ action ]( returned ); + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { diff --git a/test/unit/deferred.js b/test/unit/deferred.js index 89c9c612..fbe29070 100644 --- a/test/unit/deferred.js +++ b/test/unit/deferred.js @@ -275,6 +275,33 @@ test( "jQuery.Deferred.pipe - deferred (fail)", function() { strictEqual( value3, 6, "result of filter ok" ); }); +test( "jQuery.Deferred.pipe - context", function() { + + expect(4); + + var context = {}; + + jQuery.Deferred().resolveWith( context, [ 2 ] ).pipe(function( value ) { + return value * 3; + }).done(function( value ) { + strictEqual( this, context, "custom context correctly propagated" ); + strictEqual( value, 6, "proper value received" ); + }); + + var defer = jQuery.Deferred(), + piped = defer.pipe(function( value ) { + return value * 3; + }); + + defer.resolve( 2 ); + + piped.done(function( value ) { + strictEqual( this.promise(), piped, "default context gets updated to latest defer in the chain" ); + strictEqual( value, 6, "proper value received" ); + }); +}); + + test( "jQuery.when" , function() { expect( 23 ); From e83fcdcb02d676d91d764a58f7e8d2eb1c95de69 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 1 Jul 2011 02:11:26 +0200 Subject: [PATCH 64/66] Fixes #9682. Removes data from the options for request with no content so that it is not used again in case of a retry. Unit test added. --- src/ajax.js | 2 ++ test/unit/ajax.js | 25 ++++++++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/ajax.js b/src/ajax.js index e4e48dc7..650f3318 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -644,6 +644,8 @@ jQuery.extend({ // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter diff --git a/test/unit/ajax.js b/test/unit/ajax.js index 9f084136..33433922 100644 --- a/test/unit/ajax.js +++ b/test/unit/ajax.js @@ -321,25 +321,40 @@ test("jQuery.ajax() - responseText on error", function() { test(".ajax() - retry with jQuery.ajax( this )", function() { - expect( 1 ); + expect( 2 ); stop(); - var firstTime = 1; + var firstTime = true, + previousUrl; jQuery.ajax({ url: url("data/errorWithText.php"), error: function() { if ( firstTime ) { - firstTime = 0; + firstTime = false; jQuery.ajax( this ); } else { ok( true , "Test retrying with jQuery.ajax(this) works" ); - start(); + jQuery.ajax({ + url: url("data/errorWithText.php"), + data: { x: 1 }, + beforeSend: function() { + if ( !previousUrl ) { + previousUrl = this.url; + } else { + strictEqual( this.url , previousUrl, "url parameters are not re-appended" ); + start(); + return false; + } + }, + error: function() { + jQuery.ajax( this ); + } + }); } } }); - }); test(".ajax() - headers" , function() { From e6f8951983b8ce1af8986651fd412f9e569504c6 Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 1 Jul 2011 02:18:05 +0200 Subject: [PATCH 65/66] Fixes #9632. Adds res:// protocol to the list of local protocols. --- src/ajax.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ajax.js b/src/ajax.js index 650f3318..087f2feb 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -7,7 +7,7 @@ var r20 = /%20/g, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, + rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, From bb7d98f018c284a27b286a819238bac5541aad5e Mon Sep 17 00:00:00 2001 From: Denis Knauf Date: Thu, 7 Jul 2011 12:13:10 +0200 Subject: [PATCH 66/66] input type=datetime-local support for ajax. --- src/ajax.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ajax.js b/src/ajax.js index 087f2feb..355fd7e4 100644 --- a/src/ajax.js +++ b/src/ajax.js @@ -5,7 +5,7 @@ var r20 = /%20/g, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL - rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/,