S
S
Sergey Nikolaev2015-09-01 16:43:25
JavaScript
Sergey Nikolaev, 2015-09-01 16:43:25

How to unsubscribe from Socket.IO sockets?

Let's say we have a factory:

var socket = io.connect('ip');
        return {
            on: function (eventName, callback) {
                socket.on(eventName, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        callback.apply(socket, args);
                    });
                });
            },
            emit: function (eventName, data, callback) {
                socket.emit(eventName, data, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback.apply(socket, args);
                        }
                    });
                })
            }
        };

with its help, you can simply subscribe and catch responses, in the controller / directive of angular
socketIo.emit('subscribe', 'needThis');
socketIo.on('needThis', function(data){
           console.log(data);
 });

The question is how to unsubscribe from needThis ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2015-09-01
@Devastor

socket.removeAllListeners("needThis");

A
Andrey, 2015-09-04
@AndyGrom

function needThis(data){
    console.log(data);
}
socketIo.on('needThis', needThis);
socketIo.removeListener('needThis', needThis);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question