[英]socket.io get socket inside a callback
我正在使用socket.io作為node.js. 如果你添加這樣的事件處理程序:
io = require('socket.io')(http);
io.on('connect',function(socket){
socket.on('some event',function(arg1,arg2){
/// using socket to emit events for example
}
}
然后我可以在'some event'的回調中訪問socket但是如果我像這樣使用它
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來獲取socket.id所以我可以知道誰調用了這個事件。 謝謝
好吧,如果我明白你想做什么,你可以簡單地說:
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)
好吧,所以在討論之后,一個潛在的解決方案就是從傳遞給on
方法的anoymous回調函數中調用你的命名函數。
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
}
我經常使用Lodash的部分功能來解決這樣的問題( 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.