Skip to content

Commit aa2e57a

Browse files
committed
Avoid memory leaks by remove event arrays
When subscribing and then unsubscribing from many different types of events, it can be observed that the `Emitter._callbacks` object starts to grow. This happens because, when unsubscribing, the event specific event array is not removed when the last subscriber unsubscribes.
1 parent 4d18307 commit aa2e57a

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ Emitter.prototype.removeEventListener = function(event, fn){
109109
break;
110110
}
111111
}
112+
113+
// Remove event specific arrays for event types that no
114+
// one is subscribed for to avoid memory leak.
115+
if (callbacks.length === 0) {
116+
delete this._callbacks['$' + event];
117+
}
118+
112119
return this;
113120
};
114121

test/emitter.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,32 @@ describe('Emitter', function(){
142142

143143
calls.should.eql([]);
144144
})
145+
146+
it('should remove event array to avoid memory leak', function() {
147+
var emitter = new Emitter;
148+
var calls = [];
149+
150+
function cb() {}
151+
152+
emitter.on('foo', cb);
153+
emitter.off('foo', cb);
154+
155+
emitter._callbacks.should.not.have.property('$foo');
156+
})
157+
158+
it('should only remove the event array when the last subscriber unsubscribes', function() {
159+
var emitter = new Emitter;
160+
var calls = [];
161+
162+
function cb1() {}
163+
function cb2() {}
164+
165+
emitter.on('foo', cb1);
166+
emitter.on('foo', cb2);
167+
emitter.off('foo', cb1);
168+
169+
emitter._callbacks.should.have.property('$foo');
170+
})
145171
})
146172

147173
describe('.off()', function(){

0 commit comments

Comments
 (0)