Babak Babak - 16 days ago 5
AngularJS Question

After loading a new route old instances of controller is still running

I have a route which is loading a page based on the parameters:

.when('/:num/:den', {
templateUrl : 'app/views/templates/home.html',
controller :"ProductContoller",
controllerAs: "product",
reloadOnSearch : false });


The problem is any time that I reload the route, there is a new instance of the controller along with all previous instances still running.
I have Socket.IO listeners in my controller to get some data from server in case of any update.

Answer

In case of anybody else have the same problem, I was using Socket.IO, and it's listeners were still running so I added socket Emitter method, removeAllListeners, which is the same method as removeListener, removeListenerEvent and off. Now when I get "$destroy" event I am removing all those listeners by just passing no arguments to the method, or I can remove specific ones by stating the name of the events or even a specific handler by stating name of the event and name of the handler function.

Following is the code from Socke.IO source!

Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn)

and this is how I passed all the needed methods to my Service:

.factory('socketio', ["$rootScope", function ($rootScope) {
        var socket = io.connect();
        console.log(socket);
        return {
            on : function (eventName, callback) {
                socket.on(eventName, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        callback.apply(socket, args);
                    });
                });

            },
            removeAllListeners : function (eventName, callback) {
                socket.removeAllListeners(eventName, callback);
            },

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

            }

        };

    }
]);
Comments