TypeScript | Socket.IO:如何引用客户端对象

时间:2016-01-28 23:20:52

标签: javascript socket.io typescript ecmascript-6 phaser-framework

我正在使用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.idthis.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

1 个答案:

答案 0 :(得分:0)

您需要访问从调用方发送的context和类范围this两者存在的唯一地方是功能注册。所以而不是:

client.on('disconnect', this.onClientDisconnect.bind(this));

做:

let self = this;
client.on('disconnect', function(){self.onClientDisconnect(this.id,this.broadcast));

更多

使用thishttps://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

的库查看有关箭头功能的提示