Skip to content

Commit

Permalink
Merge pull request #30 from mroderick/issue-29-subscribe-invalid-func…
Browse files Browse the repository at this point in the history
…tions

ISSUE-29: Subscribe should return false when using non-functions as subscribers
  • Loading branch information
mroderick committed Aug 13, 2013
2 parents e94d56a + 8d0ba51 commit 852d685
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/pubsub.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ https://github.com/mroderick/PubSubJS
* you need to unsubscribe
**/
PubSub.subscribe = function( message, func ){
if ( typeof func !== 'function'){
return false;
}

// message is not registered yet
if ( !messages.hasOwnProperty( message ) ){
messages[message] = [];
Expand Down
29 changes: 28 additions & 1 deletion test/test-subscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
PubSub,
buster,
assert,
refute,
require,
sinon
*/
Expand Down Expand Up @@ -69,7 +70,33 @@
}

// make sure all tokens are different
TestHelper.assertAllTokensDifferent( tokens );
TestHelper.assertAllTokensDifferent( tokens );
},

'should return false when subscriber argument is not a function' : function(){
var invalidSubscribers = [undefined, null, 'a string', 123, [], {}, new Date()],
topic = TestHelper.getUniqueString(),
i;

for ( i = 0; i < invalidSubscribers.length; i++ ){
assert.equals(PubSub.subscribe(topic, invalidSubscribers[i]), false);
}

assert.equals(i, invalidSubscribers.length);
},

'must not throw errors when publishing with invalid subscribers' : function(){
var invalidSubscribers = [undefined, null, 'a string', 123, [], {}, new Date()],
topic = TestHelper.getUniqueString(),
i;

for (i = 0; i < invalidSubscribers.length; i++){
PubSub.subscribe(topic, invalidSubscribers[i]);
}

refute.exception(function(){
PubSub.publish(topic, TestHelper.getUniqueString());
});
}
});

Expand Down

0 comments on commit 852d685

Please sign in to comment.