I
I
Ivan Kondratiev2016-02-15 12:20:25
Angular
Ivan Kondratiev, 2016-02-15 12:20:25

Why does socket.on('custom event') work multiple times?

Good day everyone. There is a small project on angular + socket.io + nodejs
The application has only two routes
Example:

$routeProvider.
        when('/', { 
            templateUrl: '/tpl',
            controller: 'MainCtrl'
        }).
        when('/other', { 
            templateUrl: 'other.tpl',
            controller: 'OtherCtrl'
        }).
            .otherwise({
                redirectTo: '/'
            });

On first boot attached everything works as expected,
socket.on( 'new user' , function ( data ){
            console.log(1);
            $scope.UserList.push(JSON.parse(data));
});

but when you "walk" along the routes, then some functions are called several times.
$scope.UserList.push(JSON.parse(data));
The code above will work several times (it all depends on how many times I changed the url)
For example, I changed the url five times - push()
socket worked 5 times - delivered to the service
--------------- -----------------------
MyApp.factory('socket', ['$rootScope', function ($rootScope) {

    var safeApply = function(scope, fn) {
        if (scope.$$phase) {
            fn();
        } else {
            scope.$apply(fn);
        }
    };

    var socket = io.connect(URL_TO_SOCKET);

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

}]);

Tell me how to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2016-02-15
@inik23

Because you need to manually unsubscribe from the event when the controller scope is destroyed. Start here stackoverflow.com/questions/9418697/how-to-unsubsc...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question