Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aheckmann/870706 to your computer and use it in GitHub Desktop.
Save aheckmann/870706 to your computer and use it in GitHub Desktop.
.once should only accept instanceof function
From c63e6596de69ef318a31633710f2f6ed9669a877 Mon Sep 17 00:00:00 2001
From: Aaron Heckmann <aaron.heckmann+github@gmail.com>
Date: Tue, 15 Mar 2011 09:01:24 -0400
Subject: [PATCH 1/2] EventEmitter#once only takes instanceof function
---
lib/events.js | 4 ++++
1 files changed, 4 insertions(+), 0 deletions(-)
diff --git a/lib/events.js b/lib/events.js
index 2d2d5d1..9b13c80 100644
--- a/lib/events.js
+++ b/lib/events.js
@@ -137,6 +137,10 @@ EventEmitter.prototype.addListener = function(type, listener) {
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
+ if ('function' !== typeof listener) {
+ throw new Error('.once only takes instances of Function');
+ }
+
var self = this;
self.on(type, function g() {
self.removeListener(type, g);
--
1.7.0.4
From b94899534ca01f56d4eda616c87bf5eb52deb182 Mon Sep 17 00:00:00 2001
From: Aaron Heckmann <aaron.heckmann+github@gmail.com>
Date: Tue, 15 Mar 2011 09:17:49 -0400
Subject: [PATCH 2/2] add test for .once accepting functions only
---
test/simple/test-event-emitter-once.js | 5 +++++
1 files changed, 5 insertions(+), 0 deletions(-)
diff --git a/test/simple/test-event-emitter-once.js b/test/simple/test-event-emitter-once.js
index fb17237..a094dc3 100644
--- a/test/simple/test-event-emitter-once.js
+++ b/test/simple/test-event-emitter-once.js
@@ -24,6 +24,11 @@ var assert = require('assert');
var events = require('events');
var e = new events.EventEmitter();
+
+assert.throws(function () {
+ e.once('kaboom');
+}, /instances of/);
+
var times_hello_emited = 0;
e.once('hello', function(a, b) {
--
1.7.0.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment