简体   繁体   English

Socket.io“开启”功能-传递其他参数

[英]Socket.io “on” function - pass additional parameters

I can't find a nice way to pass additional parameters to socket.io 'on' handler, ie: 我找不到将其他参数传递给socket.io'on'处理程序的好方法,即:

var someEventHandler = require('someEventHandler'),
    additionalData = {test: 1};
socket.on('event', someEventHandler);

Now I want to access additionalData object inside someEventHandler function which is located in another file. 现在,我想访问位于另一个文件中的someEventHandler函数内部的AdditionalData对象。 Is there a similar way to pass arguments to handlers like jQuery 'on' gives us? 有没有类似的方法可以将参数传递给jQuery'on'这样的处理程序呢? ( $obj.on('event', '.selector', dataObject, handlerFunction) ) $obj.on('event', '.selector', dataObject, handlerFunction)

You can use another function to handle the event, which then passes whatever additional data you need. 您可以使用另一个函数来处理事件,然后传递所需的任何其他数据。 Example: 例:

var someEventHandler = require('someEventHandler'),
    additionalData = {test: 1};
socket.on('event', function(e) { someEventHandler(e, additionalData); } );

Since you don't like wrapping the callback yourself, you can change the socket.on function to make it match your desires. 由于您不喜欢自己包装回调,因此可以更改socket.on函数以使其符合您的需求。 Something like 就像是

const originalOn = socket.on;
socket.on = function (event, data, callback) {
    return originalOn.call(socket, event, (e) => callback(e, data));
};

You can now use it like so: 您现在可以像这样使用它:

let data = {/* important data */};
socket.on('importantEvent', data, (e, additionalData) => {
    // Have fun with your data
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM