From 144b2a5338e681965be2d39a0514abc3864a1046 Mon Sep 17 00:00:00 2001 From: Jeremy Martin Date: Sun, 28 Nov 2010 01:03:14 -0500 Subject: [PATCH] Fix number of args emitted by EventEmitter during "fast case" (lte 3 args) --- lib/events.js | 21 +++++++++++------ test/simple/test-event-emitter-num-args.js | 27 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 test/simple/test-event-emitter-num-args.js diff --git a/lib/events.js b/lib/events.js index cf9651abb6..ef277372de 100644 --- a/lib/events.js +++ b/lib/events.js @@ -22,20 +22,27 @@ EventEmitter.prototype.emit = function (type) { if (!handler) return false; if (typeof handler == 'function') { - if (arguments.length <= 3) { - // fast case - handler.call(this, arguments[1], arguments[2]); - } else { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; // slower - var args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); + default: + var args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } return true; } else if (isArray(handler)) { var args = Array.prototype.slice.call(arguments, 1); - var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); diff --git a/test/simple/test-event-emitter-num-args.js b/test/simple/test-event-emitter-num-args.js new file mode 100644 index 0000000000..93a5149cc7 --- /dev/null +++ b/test/simple/test-event-emitter-num-args.js @@ -0,0 +1,27 @@ +common = require("../common"); +assert = common.assert +var events = require('events'); + +var e = new events.EventEmitter(), + num_args_emited = []; + +e.on("numArgs", function() { + var numArgs = arguments.length; + console.log("numArgs: " + numArgs); + num_args_emited.push(numArgs); +}); + +console.log("start"); + +e.emit("numArgs"); +e.emit("numArgs", null); +e.emit("numArgs", null, null); +e.emit("numArgs", null, null, null); +e.emit("numArgs", null, null, null, null); +e.emit("numArgs", null, null, null, null, null); + +process.addListener("exit", function () { + assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); +}); + +