Skip to content

Commit

Permalink
Merge pull request #74 from bripkens/master
Browse files Browse the repository at this point in the history
Avoid memory leaks by removing event arrays
  • Loading branch information
vendethiel authored Nov 28, 2017
2 parents 187492a + aa2e57a commit 092199b
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 @@ -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;
};

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 092199b

Please sign in to comment.