【问题标题】:Remove specific class method listener from socket.io从 socket.io 中删除特定的类方法监听器
【发布时间】:2017-08-17 23:51:48
【问题描述】:

我在一个类中使用 socket.io-client,所以我这样做:

constructor() {
   socket.on("a", this.a.bind(this));
   socket.off("a", this.a.bind(this));
}

但是当我构造时(onoff 都触发),套接字仍然监听“a”。

我测试这个的方法是在a方法上输入console.log,输入,当收到“a”时,控制台记录事件。

我也试过socket.removeListener,但没用。

也许是因为它是一个类方法?我该如何解决这个问题?

【问题讨论】:

  • 它监听是因为请求中的“keep alive”标头。你无法解决这个问题。
  • @RomanC 如果我这样做:socket.removeAllListeners("a") 它会停止此侦听器,因此有办法停止它。我正在寻找更具体的方式
  • 它不起作用。
  • @RomanC 你为什么这么说?它确实有效,可以删除所有侦听器。
  • 你有哪个协议套接字?

标签: socket.io


【解决方案1】:

this.a.bind(this) 每次都会返回一个唯一的函数,因此当您尝试使用 .off() 并再次调用 .bind() 时,您会得到一个不同的函数,因此它与原始函数不匹配,因此 .off() 不会'找不到要删除的任何匹配函数。

您必须将原始绑定函数保存在某处。您没有显示足够多的代码上下文,无法知道保存原始 .bind() 结果的好地方。

从概念上讲,你想做这样的事情:

// save this somewhere that is per-instance and that both methods can access
// perhaps as an instance variable from the constructor
this.boundA = this.a.bind(this);

ngOnInit() {
   socket.on("a", this.boundA);
}
ngOnDestroy() {
   socket.off("a", this.boundA);
}

问题演示:

class Foo {
  constructor() {
    console.log(this.a.bind(this) === this.a.bind(this))
  }
  a() {
   
  }
}

let f = new Foo();

【讨论】:

  • 我不知道 bind 创建了一个独特的函数,我将更改逻辑以反映上述内容,并将更新。 (大约一天)谢谢。
  • @Amit - 在我添加到答案中的 sn-p 中自己尝试一下。
  • 谢谢!请查看编辑,因为即使我保存在不同的变量中它仍然无法工作
  • 我的错误,我有一个调用回调函数的函数,而不是将其传递给套接字。改变了,它工作了
猜你喜欢
  • 2014-05-30
  • 1970-01-01
  • 2016-12-25
  • 2012-08-25
  • 2018-05-13
  • 2019-02-01
  • 2022-01-17
  • 1970-01-01
  • 2021-06-01
相关资源
最近更新 更多