diff --git a/lib/events.js b/lib/events.js index 5188205d129..8c02a558ec7 100644 --- a/lib/events.js +++ b/lib/events.js @@ -170,9 +170,15 @@ EventEmitter.prototype.once = function(type, listener) { if (typeof listener !== 'function') throw TypeError('listener must be a function'); + var fired = false; + function g() { this.removeListener(type, g); - listener.apply(this, arguments); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } } g.listener = listener; diff --git a/test/simple/test-event-emitter-once.js b/test/simple/test-event-emitter-once.js index 1f0a2075da7..2eaebcc7a5e 100644 --- a/test/simple/test-event-emitter-once.js +++ b/test/simple/test-event-emitter-once.js @@ -47,3 +47,19 @@ process.on('exit', function() { assert.equal(1, times_hello_emited); }); +var times_recurse_emitted = 0; + +e.once('e', function() { + e.emit('e'); + times_recurse_emitted++; +}); + +e.once('e', function() { + times_recurse_emitted++; +}); + +e.emit('e'); + +process.on('exit', function() { + assert.equal(2, times_recurse_emitted); +});