我正在为node.js使用socket.io。如果像这样添加事件处理程序:
io = require('socket.io')(http);
io.on('connect',function(socket){
socket.on('some event',function(arg1,arg2){
/// using socket to emit events for example
}
}然后,我可以访问回调中的套接字来获取“某些事件”,但是如果我像这样使用它会怎么样呢?
io = require('socket.io')(http);
io.on('connect',function){
socket.on('some event',myfunction);
}
function myFunction(arg1,arg2)
{
//I want to use calling socket here.
}在后一种情况下如何访问套接字?我需要套接字来获取socket.id,这样我就可以知道是谁调用了这个事件。谢谢
发布于 2017-06-29 20:29:12
好吧,如果我知道你想做什么,你可以简单的说:
io = require('socket.io')(http);
io.on('connect',function){
socket.on('some event',myfunction);
}
function myFunction(arg1,arg2)
{
var socketId = this.id; //here you go, you can refer the socket with "this"
}这是我通常用来保持代码整洁的方法:
var on_potato = function(potatoData){
var socket = this;
var id = socket.id;
//use potatoData and socket here
};
var on_tomato = function(tomatoData){
var socket = this;
var id = socket.id;
//use tomatoData and socket here
};
var handleClientConnection = function (client) {
client.on('potato', on_potato);
client.on('tomato', on_tomato);
};
io.on('connection', handleClientConnection)发布于 2015-06-18 07:04:33
好的,在讨论完这一点之后,一个可能的解决方案是从传递给on方法的无源回调函数中调用您的命名函数。
io.on('connect', function(socket){
socket.on('someEvent', function(username, date){
// If you emitted an object, you'll need to parse the incoming data. So say
// You emitted {username: 'SomeName', date: 'SomeDate' }
// You could just pass data.username and data.date directly
// or put them into local variables, like:
//var username = data.username, date = data.date;
// Invoke your named function here and you can pass
// whatever you want to it, along with the socket
myFunction(username, date, socket)
})
})
myFunction(username, date, socket){
// Do whatever you're doing with the passed paramaters
}发布于 2015-06-18 06:28:42
我经常使用Lodash的partial函数来解决这样的问题(Underscore也有一个函数,它做同样的事情)。基本上,它所做的是创建一个新函数,其中填充了原始函数的一些参数。所以你会这样做:
io = require('socket.io')(http);
io.on('connect', function(socket) {
socket.on('some event', _.partial(myfunction, socket));
});
function myFunction(socket, ...args) {
// whatever you wanna do
}然后,当新的curried函数从部分执行返回时,它将socket预先填充为第一个参数,您可以根据自己的喜好使用它。
只需注意,...args只是您想放在其中的任何内容的占位符。此外,我不确定socket.io是否在触发回调时将任何内容传递给函数,这可能会影响参数在curried函数中的位置。如果socket不应该是第一个参数,你可以让它成为第二个参数:
io = require('socket.io')(http);
io.on('connect', function(socket)){
socket.on('some event', _.partial(myfunction, _, socket));
}
function myFunction(arg1, socket, ...args) {
// whatever you wanna do
}https://stackoverflow.com/questions/30903162
复制相似问题