Skip to content
This repository has been archived by the owner on May 17, 2021. It is now read-only.

Commit

Permalink
Add listener type check
Browse files Browse the repository at this point in the history
Closes #112
  • Loading branch information
Olical committed Jun 10, 2016
1 parent edee0e0 commit 64f2a38
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
14 changes: 14 additions & 0 deletions EventEmitter.js
Expand Up @@ -118,6 +118,16 @@
return response || listeners;
};

function isValidListener (listener) {
if (typeof listener === 'function' || listener instanceof RegExp) {
return true
} else if (listener && typeof listener === 'object') {
return isValidListener(listener.listener)
} else {
return false
}
}

/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
Expand All @@ -129,6 +139,10 @@
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListener = function addListener(evt, listener) {
if (!isValidListener(listener)) {
throw new TypeError('listener must be a function');
}

var listeners = this.getListenersAsObject(evt);
var listenerIsWrapped = typeof listener === 'object';
var key;
Expand Down
6 changes: 6 additions & 0 deletions tests/tests.js
Expand Up @@ -146,6 +146,12 @@

assert.strictEqual(count, 1);
});

test('it throws if you try to add a non-function/regex listener', function () {
assert.throws(ee.addListener.bind(ee, 'foo', null), /listener must be a function/)
assert.throws(ee.addListener.bind(ee, 'foo'), /listener must be a function/)
assert.throws(ee.addListener.bind(ee, 'foo', 'lol'), /listener must be a function/)
})
});

suite('addOnceListener', function () {
Expand Down

0 comments on commit 64f2a38

Please sign in to comment.