我正在使用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
答案 0 :(得分:0)
您需要访问从调用方发送的context
和类范围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