S
S
Sergey2017-02-19 12:32:57
Angular
Sergey, 2017-02-19 12:32:57

How to get rid of multiple factory call in AngularJS controller when using router?

Good afternoon, there is a factory:

app.factory('socketio', ['$rootScope', function ($rootScope) {
    var socket = io.connect('/');
    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);
                    }
                });
            })
        }
    };
}]);

It is connected to the controller that is bound to the router, that is, when switching tabs, a multiple factory call is created, and event handlers fire a proportional number of times
app.controller("some_controller", [
    'socketio',
    function (socketio) {
        var self = this;
        socketio.emit('load_data',{});
        socketio.on('load_data', function (data) {
                // срабатывает пропорцианально открытию роута
                console.log(data);
        });
    }
]);

Can you please tell me how to destroy the event listener when switching tabs so that calls are not duplicated?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2017-02-19
@evd1ser

In general, it turned out to be cured with the library https://github.com/btford/angular-socket-io and deleting during destroy, the code may be useful to someone:

app.controller("some_controller", [
    'angular-socket-io',
    '$scope',
    function (socketio, $scope) {
        var self = this;
        socketio.emit('load_data',{});
        socketio.on('load_data', function (data) {
                console.log(data);
        });
        $scope.$on('$destroy', function () {
            socket.removeListener('load_data');
        });

    }
]);

Option 2 to add the removeListener method to the original factory (peeped in the angular-socket-io library) and call it instead of connecting the library
removeListener: function (ev, fn) {
            if (fn && fn.__ng) {
                arguments[1] = fn.__ng;
            }
            return socket.removeListener.apply(socket, arguments);
        }

When the view is destroyed, the handler from the event is removed =) thank you all

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question