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" ); +});