最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass more parameters for socket.on() - Stack Overflow

programmeradmin5浏览0评论

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 just socket.on('myevet', myEvtHandler.bind(socket)); – Dan Heberden Commented Oct 13, 2013 at 7:59
Add a ment  | 

1 Answer 1

Reset to default 8

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);
});
发布评论

评论列表(0)

  1. 暂无评论