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

Add an onMany method to attach a callback to multiple socket events. #1594

Open
zoosphar opened this issue Oct 27, 2023 · 2 comments
Open

Add an onMany method to attach a callback to multiple socket events. #1594

zoosphar opened this issue Oct 27, 2023 · 2 comments

Comments

@zoosphar
Copy link

zoosphar commented Oct 27, 2023

When emitting multiple events of a similar functionality from the server, One has to apply a 'socket.on' listener to each one of them. Rather than what will be feasible is to have an onMany method which will take in an array of all the expected events and then fire the callback if any of the event is being emitted from the server.

@darrachequesne
Copy link
Member

Hi! This should be sufficient:

function onMany(socket, events, handler) {
  events.forEach(e => {
    socket.on(e, handler);
  });
}

onMany(socket, ["foo", "bar"], () => { /* ... */ });

What do you think?

@zoosphar zoosphar changed the title Sponsored issue: Add an onMany method to attach a callback to multiple socket events. Add an onMany method to attach a callback to multiple socket events. Nov 21, 2023
@zoosphar
Copy link
Author

Hi! This should be sufficient:

function onMany(socket, events, handler) {
  events.forEach(e => {
    socket.on(e, handler);
  });
}

onMany(socket, ["foo", "bar"], () => { /* ... */ });

What do you think?

I identified some potential issues with the solution you proposed

  1. If there are duplicate values in the array, this can lead to a socket listening to the same event multiple times.
  2. Another potential concern is that if the handler function is stateful (e.g., contains closure variables or relies on an external state), it might behave unexpectedly due to being reused for multiple event listeners.

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

No branches or pull requests

2 participants