简体   繁体   中英

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

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?

在Apply方法上,您需要通知两个参数:有效范围(该值在方法内部为“ this”)和参数数组。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM