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

时间:2013-10-07 05:08:57

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

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

3 个答案:

答案 0 :(得分:18)

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

答案 1 :(得分:1)

因此,如果您只想特定活动,可以尝试     socket.removeListener('you_event');

答案 2 :(得分:1)

也可以使用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 Client Documentation,“套接字实际上继承了Emitter类的每个方法,例如hasListenersonceoff(以删除事件侦听器)。

Emitter documentation

  
      
  • 传递eventfn以删除侦听器。
  •   
  • 传递event以删除该事件的所有侦听器。
  •   
  • 不传递任何内容以删除所有事件上的所有侦听器。
  •   
相关问题