Skip to content

Commit 6a4bd28

Browse files
committed
fix(EventEmitter): fixed a bug when emit returns false if emitter has once listener
1 parent ffbe2ed commit 6a4bd28

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/lib/utils/event-emitter/event-emitter.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ test('emits', t => {
2424

2525
eventEmitter.emit(events.CREATED, originatedValue, 2);
2626
eventEmitter.emit(events.DESTROYED, originatedValue, 2);
27+
28+
eventEmitter.removeAllListeners();
29+
30+
eventEmitter.once(events.CREATED, value => {
31+
t.is(value, originatedValue);
32+
});
33+
34+
t.is(eventEmitter.emit(events.CREATED, originatedValue), true);
35+
t.is(eventEmitter.emit(events.CREATED, originatedValue), false);
2736
});
2837

2938
test('once', t => {
@@ -118,3 +127,17 @@ test('removeAllListeners', t => {
118127
eventEmitter.emit(events.DESTROYED, 1);
119128
t.is(invokes2, m);
120129
});
130+
131+
test('eventNames', t => {
132+
const originatedValue = Symbol('data');
133+
134+
const eventEmitter = new EventEmitter<typeof originatedValue>();
135+
136+
eventEmitter.once(events.CREATED, value => {
137+
t.is(value, originatedValue);
138+
});
139+
140+
eventEmitter.emit(events.CREATED, originatedValue);
141+
142+
t.is(eventEmitter.eventNames().length, 0);
143+
});

src/lib/utils/event-emitter/event-emitter.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@ export class EventEmitter<T> implements EmitEvents<T>, ListenEvents<T> {
8484
container.splice(index, 1);
8585
}
8686

87+
if (container.length === 0) {
88+
this.deleteEventContainer(eventName);
89+
}
90+
8791
return this;
8892
}
8993

@@ -100,11 +104,14 @@ export class EventEmitter<T> implements EmitEvents<T>, ListenEvents<T> {
100104
return false;
101105
}
102106

107+
let emittedOnce = false;
108+
103109
for (const [cb] of container) {
104110
cb(value, ...args);
111+
emittedOnce = true;
105112
}
106113

107-
return container.length > 0;
114+
return emittedOnce;
108115
}
109116

110117
/**

0 commit comments

Comments
 (0)