summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTim Wood <washwithcare@gmail.com>2013-11-12 12:19:13 -0800
committerFedor Indutny <fedor.indutny@gmail.com>2013-11-13 03:21:04 +0400
commitc9d93f34311ce0a9b59ed9f4511a2e3ba69e0f25 (patch)
treef71eb3fbecbff07691e1d4a1c538bebd683483e0
parentac9cf002524d6817f4fdd42e08d4757fb0c29b5f (diff)
downloadnode-new-c9d93f34311ce0a9b59ed9f4511a2e3ba69e0f25.tar.gz
events: don't call once twice
Emitting an event within a `EventEmitter#once` callback of the same event name will cause subsequent `EventEmitter#once` listeners of the same name to be called multiple times. var emitter = new EventEmitter(); emitter.once('e', function() { emitter.emit('e'); console.log(1); }); emitter.once('e', function() { console.log(2); }); emitter.emit('e'); // Output // 2 // 1 // 2 Fix the issue, by calling the listener method only if it was not already called.
-rw-r--r--lib/events.js8
-rw-r--r--test/simple/test-event-emitter-once.js16
2 files changed, 23 insertions, 1 deletions
diff --git a/lib/events.js b/lib/events.js
index 5188205d12..8c02a558ec 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 1f0a2075da..2eaebcc7a5 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);
+});