alex-phillips alex-phillips - 1 year ago 176
Javascript Question

ES6: Emitting events from static methods

What is the best way, or is there a best practice or workaround, to emit an event from a static method call?

Let's say I have a ES6 class that calls

and uploads files in a directory recursively to some endpoint and I want an event emitted after each individual file is successfully uploaded. I know I can have the class inherit
, but the
functions don't exist without instantiating a new instance of the class. Is there any way around this?

Answer Source

There is no way around it. If you want to call .emit(), then you need an instance of EventEmitter somewhere that you can call the .emit() on. And, of course, this makes sense because your other code has to have something to call .on() with to register listeners on.

If you don't need a separate emitter for every object, you can make just one shared emitter that you either store in some other object, in some useful scope or in module scope or you can even make the single emitter be a class static. If the emitter instance is a class static (initialized at startup), then the static methods could all reference it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download