Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Node event handler to support multiple events #8

Merged
merged 2 commits into from
Apr 1, 2024

Conversation

brendantruleo
Copy link
Contributor

No description provided.

@burrows
Copy link
Owner

burrows commented Mar 29, 2024

This is great, but I think it would be a slightly nicer API to pass the event types as variadic arguments instead of as an array of types. Having the handler as the last arg makes this a little tricky, but it is possible to do as of typescript 4.0:

  on<T extends E['type']>(
    ...args: [T, ...T[], EventHandler<C, E, T> | string | string[]]
  ): this {
    const types = args.slice(0, -1) as T[];
    const handler = args[args.length - 1] as
      | EventHandler<C, E, T>
      | string
      | string[];

    for (const type of types) {
      this.handlers[type] =
        typeof handler === 'string' || Array.isArray(handler)
          ? () => ({ goto: handler })
          : handler;
    }

    return this;
  }

This allows you to do this:

s.on('FOO', 'BAR', BAZ', (ctx, evt) => {});

instead of this:

s.on(['FOO', 'BAR', BAZ'], (ctx, evt) => {});

This also has the added benefit of preventing an empty list of event types, which the array approach would not catch.

This issue led me to the solution above.

@brendantruleo
Copy link
Contributor Author

@burrows Cool I didn't know about variadic tuple typing and I agree I like that API better. Updated here b217818.

@burrows burrows merged commit c066edb into burrows:main Apr 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants