Skip to content

Commit 1d6e715

Browse files
Zsolt BorbélyLaszloLango
authored andcommitted
Fix EventEmitter.removeListener() (#1006)
Remove the <event> property also, when there is no other listener for that event. Now the EventEmitter.emit() returns with the correct value. Fix minor style issues as well. IoT.js-DCO-1.0-Signed-off-by: Zsolt Borbély [email protected]
1 parent 13b0fb1 commit 1d6e715

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

src/js/events.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,15 @@ EventEmitter.prototype.removeListener = function(type, listener) {
106106
if (list[i] == listener ||
107107
(list[i].listener && list[i].listener == listener)) {
108108
list.splice(i, 1);
109+
if (!list.length) {
110+
delete this._events[type];
111+
}
109112
break;
110113
}
111114
}
112115
}
113116

114117
return this;
115-
116118
};
117119

118120

test/run_pass/test_events.js

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,22 +39,22 @@ assert.equal(onceCnt, 1);
3939

4040
{
4141
var emit_test = new EventEmitter();
42-
emit_test._events=false;
42+
emit_test._events = false;
4343
emit_test.emit();
4444
}
4545
{
4646
var emit_test = new EventEmitter();
47-
emit_test._events.error=false;
47+
emit_test._events.error = false;
4848
emit_test.emit(null);
4949
}
5050
{
5151
var emit_test = new EventEmitter();
52-
emit_test._events=false;
52+
emit_test._events = false;
5353
assert.throws(function() { emit_test.addListener(null, null); }, TypeError);
5454
}
5555
{
5656
var emit_test = new EventEmitter();
57-
emit_test._events=false;
57+
emit_test._events = false;
5858
emit_test.addListener('event', function() { });
5959
}
6060
{
@@ -228,4 +228,22 @@ assert.equal(removableListenerCnt, 0);
228228
emitter.removeListener('onceRemove', removableListener);
229229
emitter.emit('onceRemove');
230230
assert.equal(removableListenerCnt, 0,
231-
'a listener for a "once" typed evet should be removable');
231+
'a listener for a "once" typed event should be removable');
232+
233+
/*
234+
* Test when the last listener is removed from an object,
235+
* the related property doesn't exist anymore.
236+
*/
237+
var listener1 = function() {
238+
};
239+
240+
emitter.addListener('event1', listener1);
241+
emitter.removeListener('event1', listener1);
242+
var res = emitter.emit('event1');
243+
assert.equal(res, false);
244+
245+
emitter.addListener('event2', listener1);
246+
emitter.addListener('event2', listener1);
247+
emitter.removeAllListeners('event2');
248+
res = emitter.emit('event2');
249+
assert.equal(res, false);

0 commit comments

Comments
 (0)