Reputation: 165
I try to stop listening in socket.io. For example, in my case, I get the data from a socket like this.
Socket.on('event', function(data) {}}
How can I stop listening in socket.io? Thanks
Upvotes: 1
Views: 3457
Reputation: 46
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
Upvotes: 2
Reputation: 858
To unsubscribe all listeners of an event
socket.off('event-name');
To unsubscribe a certain listener
socket.off('event-name', listener);
Or You can use following things also,
socket.removeListener(eventName, listener)
socket.removeAllListeners([eventName])
Ref: https://socket.io/docs/server-api/#socket-removeListener-eventName-listener
Upvotes: 6
Reputation: 3309
socket.close()
or socket.disconnect()
Returns Socket
Disconnects the socket manually.
socket.off('event', function(){})
Unbind the specified event handler (opposite of .on()).
If you decide to use this method, be careful! socket.off() does not stop the this client-side socket from receiving any server-sent messages, it just prevents the specified event handler from firing.
Actually, a socket instance inherits every method from Emitter
class (https://github.com/component/emitter), so you can use .hasListeners()
, .once()
and already said .off()
(to remove an specific event listener).
Here you find a nice doc about these and other Socket.io methods: https://sailsjs.com/documentation/reference/web-sockets/socket-client/io-socket-on
Upvotes: 4