Skip to content

Commit

Permalink
Avoid memory leaks by remove event arrays
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bripkens committed Jan 29, 2016
1 parent 4d18307 commit aa2e57a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,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;
};

Expand Down
26 changes: 26 additions & 0 deletions test/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(){
Expand Down

0 comments on commit aa2e57a

Please sign in to comment.