diff --git a/index.js b/index.js index fa4faee..40dc0c4 100644 --- a/index.js +++ b/index.js @@ -111,6 +111,13 @@ Emitter.prototype.removeEventListener = function(event, fn){ break; } } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + return this; }; diff --git a/test/emitter.js b/test/emitter.js index 02c3a0b..a1f1dda 100644 --- a/test/emitter.js +++ b/test/emitter.js @@ -142,6 +142,32 @@ describe('Emitter', function(){ calls.should.eql([]); }) + + it('should remove event array to avoid memory leak', function() { + var emitter = new Emitter; + var calls = []; + + function cb() {} + + emitter.on('foo', cb); + emitter.off('foo', cb); + + emitter._callbacks.should.not.have.property('$foo'); + }) + + it('should only remove the event array when the last subscriber unsubscribes', function() { + var emitter = new Emitter; + var calls = []; + + function cb1() {} + function cb2() {} + + emitter.on('foo', cb1); + emitter.on('foo', cb2); + emitter.off('foo', cb1); + + emitter._callbacks.should.have.property('$foo'); + }) }) describe('.off()', function(){