Javascript 访问socket.io中发出消息的套接字
我有一个名为GameServer的类,它有处理各种socket.io消息的方法。下面是一个简单的例子:Javascript 访问socket.io中发出消息的套接字,javascript,node.js,socket.io,Javascript,Node.js,Socket.io,我有一个名为GameServer的类,它有处理各种socket.io消息的方法。下面是一个简单的例子: var GameServer = function(app, io) { this.app = app; this.io = io; this.io.on('connection', this.handleConnect.bind(this)); }; GameServer.prototype.handleConnect = function(socket) { socket
var GameServer = function(app, io) {
this.app = app;
this.io = io;
this.io.on('connection', this.handleConnect.bind(this));
};
GameServer.prototype.handleConnect = function(socket) {
socket.on('receive_a_message', this.handleMessage.bind(this));
};
GameServer.prototype.handleMessage = function(message) {
this.app.doSomethingWithMessage(message);
// here is where I want to reply/emit to the socket that sent me the message
};
不幸的是,因为我需要绑定()我的socket.io回调方法以访问其他类属性(在上面的示例中,我需要访问this.app以运行doSomethingWithMessage),所以我处于不同的上下文中
有没有办法将socket.io回调绑定到GameServer类,并仍然访问发送消息的套接字?有人能找到解决这个问题的方法吗?您已经在绑定中传递了上下文。您也可以将套接字作为绑定的一部分传递
var GameServer = function(app, io) {
this.app = app;
this.io = io;
this.io.on('connection', this.handleConnect.bind(this));
};
GameServer.prototype.handleConnect = function(socket) {
socket.on('receive_a_message', this.handleMessage.bind(this, socket));
};
GameServer.prototype.handleMessage = function(socket, message) {
this.app.doSomethingWithMessage(message);
socket.emit('a reply');
};
我还没听说过其他的争论。这是一个非常有用的解决方案。