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