Can you use `.apply()` on the emit method of EventEmitter?

Problem

I'm trying to do...

EventEmitter = require('events').EventEmitter

events = new EventEmitter()

events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3'])

...but it doesn't seem to work or throw an error, any help?

Problem courtesy of: boom

Solution

On Apply method you need inform two arguments: A valid scope (what value will be the "this" inside the method) and the argument array.

Solution courtesy of: Everton Tavares

Discussion

I think the emit() function of the EventEmitter is expecting this to be an actual EventEmitter object. The following seems to work if you pass in the events object.

events.emit.apply(events, ['eventname', 'arg1', 'arg2', 'arg3'])

Though at this point, might as well just call

emit('eventname', 'arg1', 'arg2', 'arg3')

I am guessing the emit() method is looping over an internal list of registered events to see if there is a matching one. Not sure if this helps, just something I came across today working with events...

Discussion courtesy of: cengebretson

This recipe can be found in it's original form on Stack Over Flow.