Bagel03
Bagel03

Reputation: 715

Setup event-listeners more quickly (typescript)

Very simple question: I have a codebase, which contains functions for each possible event that could be fired from Client.on():

Client.on('connect', onConnect);
Client.on('message', onMessage);
Client.on('ping', onPing);
//...

All of the valid event stings are declared in the Client.on declaration, ie.

class Client{
  public on(event: 'connect'|'message'|'ping', listener: (info: dataInfoContainer) => void): this;
}

Is there a faster way to do this? Maybe something like:

Client.on.arguments[0].types.forEach((type) => eval(`Client.on(${type}, on${type.toTileCase}`));

Upvotes: 1

Views: 40

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

I'd put all your functions like onConnect into an object indexed by event name:

const listeners = {
  connect(info: dataInfoContainer) {
    // ...
  },
  message(info: dataInfoContainer) {
  }
  // ...
};
for (const [eventName, listener] of Object.entries(listeners)) {
  Client.on(eventName as keyof typeof listeners, listener);
}

Upvotes: 4

Related Questions