我正在使用 TypeScript、socket.io 和游戏引擎 Phaser 进行测试,并在 Visual Studio 上工作
这是我的 socket.io 事件处理类的示例
class RemoteEventHandlers{
...
constructor(socket,players){
this.socket = socket;
this.players = players;
}
...
onSocketConnection(client): void{
client.on('disconnect', this.onClientDisconnect.bind(this));
client.on('new player', this.onNewPlayer.bind(this));
client.on('move player', this.onMovePlayer.bind(this));
}
onClientDisconnect(): void{
let disconnectedPlayer = this.searchPlayerById(this.id);
if (!disconnectedPlayer)
{
console.log("not found ", this.id);
return;
}
this.players.splice(this.players.indexOf(disconnectedPlayer), 1);
this.broadcast.emit('remove player', { id: this.id });
}
...
}
我需要访问当前范围的this.id
和this.broadcast
,同时我需要访问this.players
和类的方法 this.searchPlayerByid()
(这就是我使用 .bind(this)
的原因)
如果有人能给我一些提示,我将不胜感激。
更新
此代码有效:
onSocketConnection(client): void{
this.client = client;
client.on('disconnect', () => {this.client = client; this.onClientDisconnect();});
client.on('new player', data => { this.client = client; this.onNewPlayer(data);});
client.on('move player', data => { this.client = client; this.onMovePlayer(data);});
}
我可以在我的回调函数中使用 this.client.id
访问套接字 id
最佳答案
您需要访问从调用者发送的 context
this 和类作用域 this
。 两者 存在的唯一地方是在函数注册点。所以不是:
client.on('disconnect', this.onClientDisconnect.bind(this));
做:
let self = this;
client.on('disconnect', function(){self.onClientDisconnect(this.id,this.broadcast));
更多
请参阅有关使用 this
的库的箭头函数的提示:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
关于javascript - typescript |套接字IO : How to refer to the client object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074044/