Skip to content

Commit 4b17232

Browse files
committed
fix: add handler only once
1 parent b306462 commit 4b17232

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/event-emitter.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@ class EventEmitter {
2121
* @param {function} fn event handler
2222
*/
2323
on(type, fn) {
24-
(this._events[type] = this._events[type] || []).push(fn);
24+
const events = this._events[type] || (this._events[type] = []);
25+
if (events && events.some(handler => handler === fn)) {
26+
return;
27+
};
28+
events.push(fn);
2529
return this;
2630
}
2731

test/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ describe('Event Emitter', () => {
3838
assert.property(ee._events, eventName);
3939
assert.deepEqual(ee._events[eventName], [fn1, fn2]);
4040
});
41+
42+
it('should add the same handler only once', () => {
43+
const fn = () => {};
44+
const eventName = 'event';
45+
ee.on(eventName, fn);
46+
ee.on(eventName, fn);
47+
assert.property(ee._events, eventName);
48+
assert.deepEqual(ee._events[eventName], [fn]);
49+
});
4150
});
4251

4352
describe('unsubscribe handlers', () => {

0 commit comments

Comments
 (0)