For socket.on("someChannel", handler), I hope to extract out my handler function to another file. As such, they need to be passed in the socket obj and some more additional info.
Like:
socket.on("myEvt", myEvtHandler);
myEvtHandler(socket, additionalInfo, data) {//some stuff here}
But I can't. The best I can think of is to do closure:
(function(socket, addtionalInfo) {
socket.on("myEvt", function(data) {
myEvtHandler(socket, addtionalInfo, data);
});
})(socket, addtionalInfo);
Is this correct? Are there better ways?
You can create a partial function using bind:
socket.on("myEvt", myEvtHandler.bind(null, socket, additionalInfo));
The bind() will return a function with the first two arguments already 'filled in'. The first argument passed to bind() (null in this case) is going to be the this object in your handler (more info).
Any additional arguments passed by socket.io to the handler will be available from the third argument onwards:
function myEvtHandler(socket, additionalInfo, data) { ... }
Similarly, this would do (almost) the same:
socket.on("myEvt", function(data) {
myEvtHandler(socket, additionalInfo, data);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With