Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass more parameters for socket.on()

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?

like image 501
Boyang Avatar asked Dec 15 '25 02:12

Boyang


1 Answers

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);
});
like image 86
robertklep Avatar answered Dec 16 '25 17:12

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!