简体   繁体   English

我怎样才能获得Node.js类和socket.io事件上下文?

[英]How can I get Node.js class and socket.io event context?

I have a Problem with the correct context in a JavaScript class and a socket.io 'disconnect' event. 我在JavaScript类和socket.io'connect'事件中遇到了正确的上下文问题。

My class looks like so: 我的班级看起来像这样:

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
   }
}

In the "playerLeave" function I can access the socket id with "this.id". 在“playerLeave”函数中,我可以使用“this.id”访问套接字ID。 But to access the "_players" map I need the context of the class which I get if I change the "addListeners" function to: 但是要访问“_players”地图,我需要我得到的类的上下文,如果我将“addListeners”函数更改为:

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. 但是由此我松开了Event的上下文,因此可以调用“this.id”来接收套接字ID。

How can I get both? 我怎样才能得到这两个?

Can you try with something like this: 你可以尝试这样的事情:

addListeners(player) {
  player.socket.on('disconnect', this.playerLeave.bind(this));
}

playerLeave (socket) {...}

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));
   }

And the class instance will be passed as a parameter in your socketIO event : 并且类实例将作为socketIO事件中的参数传递:

   playerLeave(gameSessionInstance) {
       console.log('Bye '+this.id);
       gameSessionInstance.removePlayer(this.id); // if you have a method called removePlayer for example
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM