Reputation: 5557
I'm trying to simplify my code and break it down into multiple files. For example, I managed to do:
socket.once("disconnect", disconnectSocket);
and then have a separate function called disconnectSocket
which can access the socket
object as follows:
const disconnectSocket = socket => {
....
};
I'm trying to do something similar with this pattern:
socket.on(EVENT_NAME, params => {
...
});
where instead I can do:
socket.on(EVENT_NAME, myFunc);
const myFunc = (socket, params) => {
...
}
but this is failing and saying params is undefined
. What am I doing wrong?
Upvotes: 0
Views: 39
Reputation: 18929
You can achieve this, but your function signature is incorrect. The handler will accept only one parameter. Note that a few of the built-in events like reconnect_failed
don't pass any params.
Change your signature to:
socket.on(EVENT_NAME, myFunc);
const myFunc = (message) => {
...
}
If you want to access the socket, then do something like:
socket.on(EVENT_NAME, (message) => myFunc(socket, message));
const myFunc = (socket, message) => {
...
}
I use this exact pattern:
socket.on(constants.events.game.deployUnit, (message) => {
deployUnit(socket, message);
});
socket.on(constants.events.game.skipOpponent, (message) => {
skipOpponent(socket, message);
});
socket.on(constants.events.game.logDefenderKill, (message) => {
logDefenderKill(socket, message);
});
Upvotes: 1