【问题标题】:TypeScript | Socket.IO : How to refer to the client object打字稿 | Socket.IO:如何引用客户端对象
【发布时间】:2016-05-06 13:40:32
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您需要访问从调用者向下发送的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

    【讨论】:

    • 感谢您的回答。我发现我的代码出了什么问题,我刚刚将 client.on('new player', this.onNewPlayer.bind(this)); 替换为 client.on('new player', data => { this.client = client; this.onNewPlayer(data)}); 并且有效
    • 另外,如果我这样做 let self = this; client.on('disconnect', function(){self.onClientDisconnect(this.id,this.broadcast)); Visual Studio 会抛出错误 The property 'id' does not exist on type 'RemoteEventHandlers'
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2018-08-12
    • 2018-02-13
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多