javascript - typescript |套接字IO : How to refer to the client object

标签 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

最佳答案

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

相关文章:

Javascript 图像 slider

angular - 导入到 Controller 后,三个 JS + Angular 7 出现错误 BufferAttribute

html - 如何立即将上传的图像显示为 Canvas 背景?

javascript - 如何使用 JavaScript 将 ASCII 数字数组转换回其 char 值?

javascript灯箱效果

javascript - AngularJS:指令在页面上多次并发出/广播处理

java - 如何使用 Socket.IO-client Java 将 String 消息从 Android 发送到服务器?

amazon-web-services - 为什么使用 Socket.io 时 AWS ALB 会断开连接

javascript - 多次刷新后 Socket.io 停止工作

javascript - 如何设置多行打字效果以响应行间延迟