Skip to content

Commit 55df216

Browse files
committed
jQuery.subscribe now returns a handle that can be passed to jQuery.unsubscribe to... well... unsubscribe. Unit test amended.
1 parent 4dce543 commit 55df216

File tree

2 files changed

+37
-15
lines changed

2 files changed

+37
-15
lines changed

src/channel.js

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
(function( jQuery ) {
22

33
var channels = {},
4-
channelMethods = {
5-
publish: "fire",
6-
subscribe: "add",
7-
unsubscribe: "remove"
8-
},
94
sliceChannel = [].slice;
105

116
jQuery.Channel = function( name ) {
@@ -14,22 +9,37 @@
149
channel = name && channels[ name ];
1510
if ( !channel ) {
1611
callbacks = jQuery.Callbacks();
17-
channel = {};
18-
for ( method in channelMethods ) {
19-
channel[ method ] = callbacks[ channelMethods[ method ] ];
20-
}
12+
channel = {
13+
publish: callbacks.fire,
14+
subscribe: callbacks.add,
15+
unsubscribe: callbacks.remove
16+
};
2117
if ( name ) {
2218
channels[ name ] = channel;
2319
}
2420
}
2521
return channel;
2622
};
2723

28-
jQuery.each( channelMethods, function( method ) {
29-
jQuery[ method ] = function( name ) {
30-
var channel = jQuery.Channel( name );
31-
channel[ method ].apply( channel, sliceChannel.call( arguments, 1 ) );
32-
};
24+
jQuery.extend({
25+
subscribe: function( id ) {
26+
var channel = jQuery.Channel( id ),
27+
args = sliceChannel.call( arguments, 1 );
28+
channel.subscribe.apply( channel, args );
29+
return {
30+
channel: channel,
31+
args: args
32+
};
33+
},
34+
unsubscribe: function( id ) {
35+
var channel = id && id.channel || jQuery.Channel( id );
36+
channel.unsubscribe.apply( channel, id && id.args ||
37+
sliceChannel.call( arguments, 1 ) );
38+
},
39+
publish: function( id ) {
40+
var channel = jQuery.Channel( id );
41+
channel.publish.apply( channel, sliceChannel.call( arguments, 1 ) );
42+
}
3343
});
3444

3545
})( jQuery );

test/unit/channel.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ test( "jQuery.Channel - Named Channel", function() {
4242

4343
test( "jQuery.Channel - Helpers", function() {
4444

45-
expect( 2 );
45+
expect( 4 );
4646

4747
function callback( value ) {
4848
ok( true, "Callback called" );
@@ -53,4 +53,16 @@ test( "jQuery.Channel - Helpers", function() {
5353
jQuery.publish( "test" , "test" );
5454
jQuery.unsubscribe( "test", callback );
5555
jQuery.publish( "test" , "test" );
56+
57+
58+
var test = true,
59+
subscription = jQuery.subscribe( "test", function() {
60+
ok( test, "first callback called" );
61+
}, function() {
62+
ok( test, "second callback called" );
63+
});
64+
jQuery.publish( "test" );
65+
test = false;
66+
jQuery.unsubscribe( subscription );
67+
jQuery.publish( "test" );
5668
});

0 commit comments

Comments
 (0)