Skip to content

Instantly share code, notes, and snippets.

@jmar777
Created November 27, 2010 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmar777/718366 to your computer and use it in GitHub Desktop.
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.
// 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' }
@jmar777
Copy link
Author

jmar777 commented Nov 27, 2010

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).

@gilbertw1
Copy link

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]);
    }
}

@jmar777
Copy link
Author

jmar777 commented Nov 28, 2010

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