我正在使用WebSocket
编写一个简单的socketio
应用程序。我可以在连接和消息上实现2个套接字事件。第一个接受套接字作为参数(客户端),第二个接受客户端发送的数据。所以我可以用这种方式编写它来在消息事件中使用socket变量:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", function(msg){
console.log("i can use message: "+msg);
console.log("and the socket: "+soc.id);
});
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
但我希望将我的功能分开以提高可读性:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(){...
我需要在接收soc
的函数之外的范围内使用socket
变量。这可能吗?
答案 0 :(得分:1)
在onClientConnection函数之外初始化soc
。
var soc;
WebSocketNoaListener.onClientConnect = function(socket){
soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
现在可以在onClientConnect之外访问 soc
。
答案 1 :(得分:1)
你应该真的做这样的事情而不是污染全局空间(此外,在另外两个答案中给出的解决方案将无法处理两个同时连接,因为在每个连接处都会覆盖soc
)。 / p>
WebSocketNoaListener.onClientMessage = function(soc, msg){
console.log("i can use message: " + msg);
console.log("and the socket: " + soc.id);
};
WebSocketNoaListener.onClientDisconnect = function(soc, event){
console.log("not implemented in question");
};
WebSocketNoaListener.onClientConnect = function(socket){
socket.on("message", WebSocketNoaListener.onClientMessage.bind(this, socket));
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect.bind(this, socket));
}
答案 2 :(得分:-2)
好的,这是websocket特定的终极答案;
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(msg){
console.log("this is the message "+msg);
console.log("and this is the id of the socket "+this.id);
//'this' points here the socket itself
}