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?
The off function can also be used.
socket.off('news'); // stops listening to the "news" eventsocket.off('news', myFunction); // useful if you have multiple listeners for the same eventsocket.off(); // stops listening to all eventsAccording 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
eventandfnto remove a listener.- Pass
eventto remove all listeners on that event.- Pass nothing to remove all listeners on all events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With