Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop listening to a socket.io channel?

Tags:

socket.io

In socket.io, you can bind to a socket event/channel like this:

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

But how do you stop listening to the "news" event?

like image 939
Tim Fairbrother Avatar asked Oct 07 '13 05:10

Tim Fairbrother


1 Answers

The off function can also be used.

  • 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



Sources

According to the Socket.io Client Documentation "the socket actually inherits every method of the Emitter class, like hasListeners, once or off (to remove an event listener)."

Emitter documentation:

  • Pass event and fn to remove a listener.
  • Pass event to remove all listeners on that event.
  • Pass nothing to remove all listeners on all events.
like image 67
Michael Cox Avatar answered Oct 10 '22 02:10

Michael Cox