13

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?

dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
Tim Fairbrother
  • 928
  • 2
  • 9
  • 20
  • have a look at this answere http://stackoverflow.com/questions/9418697/how-to-unsubscribe-from-a-socket-io-subscription – Gaurav Singla Oct 07 '13 at 05:22

3 Answers3

28

Try, socket.removeAllListeners("news");

vaibhavmande
  • 1,115
  • 9
  • 17
10

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.
Michael Cox
  • 1,116
  • 2
  • 11
  • 22
1

If you want to remove only a specific event you can try socket.removeListener('you_event');

CoolMind
  • 26,736
  • 15
  • 188
  • 224