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?
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?
Share Improve this question asked Oct 13, 2013 at 7:54 BoyangBoyang 2,5765 gold badges34 silver badges50 bronze badges 1-
Did you verify that
this
in the.on
handler isn't the socket itself? if not, you can justsocket.on('myevet', myEvtHandler.bind(socket));
– Dan Heberden Commented Oct 13, 2013 at 7:59
1 Answer
Reset to default 8You 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);
});