Improve this AngularJS factory to use with socket.io

后端 未结 13 1527
你的背包
你的背包 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 08:51

    I tried with the above code in my AngularApp and found the events duplicating. With the same Example from @pootzko using the SocketIoFactory

    I have added a unSubscribe(even_name) inside the $destroy of the Controller, that will remove/clear the socketEventListner

    var app = angular.module("app", []);
    ..
    ..
    ..
    //Create a SocketIoFactory
    app.service('SocketIoFactory', function($rootScope){
    
        console.log("SocketIoFactory....");
        //Creating connection with server
        var protocol = 'ws:',//window.location.protocol,
            host = window.location.host,
            port = 80,
            socket = null;
        var nodePath = protocol+'//'+host+':'+port+'/';
    
        function listenerExists(eventName) {
            return socket.hasOwnProperty("$events") && socket.$events.hasOwnProperty(eventName);
        }
    
        return {
            connect: function () {
                socket = io.connect(nodePath);
                console.log('SOCKET CONNECTION ... ',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);
                        }
                    });
                })
            },
            unSubscribe: function(listener) {
                socket.removeAllListeners(listener);
            }
        };
    });
    
    ..
    ..
    ..
    
    //Use in a controller
    app.controller("homeControl", ['$scope', 'SocketIoFactory', function ($scope, SocketIoFactory) {
    
      //Bind the events
      SocketIoFactory.on('', function (data) {
    
      });
    
      //On destroy remove the eventListner on socketConnection
       $scope.$on('$destroy', function (event) {
            console.log('[homeControl] destroy...');
            SocketIoFactory.unSubscribe('');
        });
    }]);
    

提交回复
热议问题