From 114846d38dc05afec18158e2365d6a449851819b Mon Sep 17 00:00:00 2001 From: jaubourg Date: Fri, 6 May 2011 18:35:08 +0200 Subject: [PATCH 01/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] $.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/17] 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/17] 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 );