jQuery.subscribe now returns a handle that can be passed to jQuery.unsubscribe to... well... unsubscribe. Unit test amended.

This commit is contained in:
jaubourg 2011-05-24 21:18:08 +02:00
parent 13c330a0f8
commit b136d9cc7a
2 changed files with 37 additions and 15 deletions

View file

@ -1,11 +1,6 @@
(function( jQuery ) { (function( jQuery ) {
var channels = {}, var channels = {},
channelMethods = {
publish: "fire",
subscribe: "add",
unsubscribe: "remove"
},
sliceChannel = [].slice; sliceChannel = [].slice;
jQuery.Channel = function( name ) { jQuery.Channel = function( name ) {
@ -14,10 +9,11 @@
channel = name && channels[ name ]; channel = name && channels[ name ];
if ( !channel ) { if ( !channel ) {
callbacks = jQuery.Callbacks(); callbacks = jQuery.Callbacks();
channel = {}; channel = {
for ( method in channelMethods ) { publish: callbacks.fire,
channel[ method ] = callbacks[ channelMethods[ method ] ]; subscribe: callbacks.add,
} unsubscribe: callbacks.remove
};
if ( name ) { if ( name ) {
channels[ name ] = channel; channels[ name ] = channel;
} }
@ -25,11 +21,25 @@
return channel; return channel;
}; };
jQuery.each( channelMethods, function( method ) { jQuery.extend({
jQuery[ method ] = function( name ) { subscribe: function( id ) {
var channel = jQuery.Channel( name ); var channel = jQuery.Channel( id ),
channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) ); 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 ); })( jQuery );

View file

@ -42,7 +42,7 @@ test( "jQuery.Channel - Named Channel", function() {
test( "jQuery.Channel - Helpers", function() { test( "jQuery.Channel - Helpers", function() {
expect( 2 ); expect( 4 );
function callback( value ) { function callback( value ) {
ok( true, "Callback called" ); ok( true, "Callback called" );
@ -53,4 +53,16 @@ test( "jQuery.Channel - Helpers", function() {
jQuery.publish( "test" , "test" ); jQuery.publish( "test" , "test" );
jQuery.unsubscribe( "test", callback ); jQuery.unsubscribe( "test", callback );
jQuery.publish( "test" , "test" ); 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" );
}); });