0

I'm currently using ES6 classes. I have a scenario where one emits a message, sending the values within an instance variable, and then I need to reset the variable after emitting.

So it looks something like the following (and works as intended, but looking for a more proper way of doing so):

// in class Ace
this.emit('someEvent', this.storage, () => {
    this.storage = {};
});

// in class Bay
// Assuming `this.instanceAce` is an instance of class Ace
this.instanceAce.on('someEvent', (data, cb) => {
    // do stuff with data
    cb();
}

This works but the idea of providing a callback to an event listener is strange. This is assuming I would have exactly one listener for this event (which is currently true), but what happens in scenarios where I may have more than one listener?

Are there better alternatives to this solution? Something that does not seem to sort of ignore the purpose of the event model?

philip yoo
  • 2,462
  • 5
  • 22
  • 37

1 Answers1

1

It's not clear exactly what you're trying to do, but if you just want to clear the this.storage before any of your listeners might get the message from .emit() to avoid any race conditions, then you could do this:

// Send storage and re-initialize the storage once we've captured it for sending
let temp = this.storage;
this.storage = {};
this.emit('someEvent', temp);

Note: The regular EventEmitter object does not support the callback that you were using. There are some extensions of EventEmitter that do support that model, but not the base EventEmitter object as you can see here in the doc. We could probably help you better if we knew which exact object you were using (apparently one that does support such a callback).

jfriend00
  • 683,504
  • 96
  • 985
  • 979