jQuery.subscribe now returns a handle that can be passed to jQuery.unsubscribe to... well... unsubscribe. Unit test amended.
This commit is contained in:
parent
4dce543ee6
commit
55df216125
2 changed files with 37 additions and 15 deletions
|
@ -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 );
|
||||
|
|
|
@ -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" );
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue