Created
November 27, 2010 23:00
-
-
Save jmar777/718366 to your computer and use it in GitHub Desktop.
The EventEmitter appears to pass a minimum of two arguments to any bound event handlers, regardless of how many arguments are passed to the emit() function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// using node v0.2.4 | |
var sys = require('sys'), | |
events = require('events'); | |
// create a custom EventEmitter | |
function CustomEmitter() { | |
// call "super" constructor | |
events.EventEmitter.call(this); | |
} | |
// inherit from EventEmitter | |
sys.inherits(CustomEmitter, events.EventEmitter); | |
// create a test instance | |
var test = new CustomEmitter(); | |
// bind a handler to the 'foo' event | |
test.on('foo', function() { | |
// log the arguments | |
console.log(arguments); | |
}); | |
// run some tests: | |
test.emit('foo'); | |
// logs 2 args: { '0': undefined, '1': undefined } | |
test.emit('foo', 'bar'); | |
// logs 2 args: { '0': 'bar', '1': undefined } | |
test.emit('foo', 'bar', 'baz'); | |
// logs 2 args: { '0': 'bar', '1': 'baz' } | |
test.emit('foo', 'bar', 'baz', 'hello', 'world'); | |
// logs 4 args: { '0': 'bar', '1': 'baz', '2': 'hello', '3': 'world' } | |
How big of a performance hit would you take by potentially removing the 'fast' case?
You could maybe do it this much less elegant way to get the best of both worlds:
if (arguments.length <= 3) {
// fastish case
if(arguments.length == 0) {
handler.call(this);
} else if(arguments.length == 1) {
handler.call(this, arguments[1]);
} else {
handler.call(this, arguments[1], arguments[2]);
}
}
I agree. It was suggested in the IRC channel (by webr3) to simply handle the "fast cases" (0-5 arguments or so) with a switch/case, and then do the Array.prototype.slice for higher numbers of arguments. I generally like the idea - think it would make sense to run some actual tests though to see where the hand-off should occur.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: the source of the unexpected arguments is line 27 of events.js (https://github.com/ry/node/blob/v0.2.4/lib/events.js). This behavior exists all the way up through label v0.3.1 (currently the latest).