如何获取Node.js类和socket.io事件上下文? [英] How can I get Node.js class and socket.io event context?
问题描述
我在JavaScript类和socket.io'disconnect'事件中存在正确上下文的问题。
I have a Problem with the correct context in a JavaScript class and a socket.io 'disconnect' event.
我的类如下:
class GameSession {
constructor(gameSessionId) {
this._gameSessionId = gameSessionId;
this._players = new Map();
}
addPlayer(socketId,player) {
this._players.set(socketId,player);
this.addListeners(player);
}
addListeners(player) {
player.socket.on('disconnect',this.playerLeave);
}
playerLeave () {
// ##### here is my Problem
}
}
在 playerLeave功能中,我可以使用 this.id访问套接字ID。但是要访问 _players映射,我需要获得类的上下文,如果我将 addListeners函数更改为:
In the "playerLeave" function I can access the socket id with "this.id". But to access the "_players" map I need the context of the class which I get if I change the "addListeners" function to:
addListeners(player) {
player.socket.on('disconnect',() => this.playerLeave());
}
但是,这样我松开了事件的上下文,因此可以调用
But by this I loose the context of the Event and so the possebility to call "this.id" to receive the socket id.
如何同时获得两者?
推荐答案
我遇到了同样的问题,并且找到了解决方案。 (我希望您也能找到它!)
I was facing the same issue, and I found a solution. (I hope you found it too!)
您只需要绑定两个实例:
You just have to bind both of instances like this:
addListeners(player) {
var playerSocket = player.socket;
playerSocket.on('disconnect',this.playerLeave.bind(playerSocket, this));
}
该类实例将作为参数传递给您的socketIO事件: / p>
And the class instance will be passed as a parameter in your socketIO event :
playerLeave(gameSessionInstance) {
console.log('Bye '+this.id);
gameSessionInstance.removePlayer(this.id); // if you have a method called removePlayer for example
}
这篇关于如何获取Node.js类和socket.io事件上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!