Improve this AngularJS factory to use with socket.io

后端 未结 13 1508
你的背包
你的背包 2020-12-07 08:42

I want to use socket.io in AngularJS. I found the following factory:

app.factory(\'socket\', function ($rootScope) {
    var socket = io.connect();
    retur         


        
13条回答
  •  日久生厌
    2020-12-07 09:03

    I solved this problem by checking whether listener already exists. If you have multiple controllers that are all loaded at the same time (think of different page modules that all utilize socketIO), removing all registered listeners on $destroy would break the functionality of both the destroyed controller and all the controllers that are still loaded.

    app.factory("SocketIoFactory", function ($rootScope) {
        var socket = null;
        var nodePath = "http://localhost:12345/";
    
        function listenerExists(eventName) {
            return socket.hasOwnProperty("$events") && socket.$events.hasOwnProperty(eventName);
        }
    
        return {
            connect: function () {
                socket = io.connect(nodePath);
            },
            connected: function () {
                return socket != null;
            },
            on: function (eventName, callback) {
                if (!listenerExists(eventName)) {
                    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);
                        }
                    });
                })
            }
        };
    });
    

    This could be further improved by tracking which listeners were registered by which controller and removing only listeners that belong to destroyed controllers to clean up the memory.

提交回复
热议问题