你怎么停止听socket.io频道?

Tim*_*her 10 socket.io

在socket.io中,您可以像这样绑定到套接字事件/通道:

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
   socket.on('news', function (data) {
   console.log(data);
   socket.emit('my other event', { my: 'data' });
 });
</script>
Run Code Online (Sandbox Code Playgroud)

但是你怎么不再听"新闻"事件呢?

小智 23

尝试, socket.removeAllListeners("news");


Mic*_*Cox 9

off也可以使用该功能。

  • socket.off('news'); // stops listening to the "news" event
  • socket.off('news', myFunction); // useful if you have multiple listeners for the same event
  • socket.off(); // stops listening to all events



来源

根据Socket.io 客户端文档“套接字实际上继承了 Emitter 类的每个方法,如hasListeners, onceor off(删除事件侦听器)。

发射器文档

  • 通过eventfn删除侦听器。
  • 通过event以删除该事件的所有侦听器。
  • 不传递任何内容以删除所有事件的所有侦听器。