Improve this AngularJS factory to use with socket.io

后端 未结 13 1464
你的背包
你的背包 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:17

    Expanding on Brandon's answer above, I've created a service that should additionally 1) strip angular tags like .$$hashKey that gets left on elements, and 2) allows for namespaced sockets like socketsof('..').on('..'

    (function (window, app, undefined) {
        'use strict';
    
    
        var ScopedSocket = function (socket, $rootScope) {
            this.socket = socket;
            this.$rootScope = $rootScope;
            this.listeners = [];
            this.childSockets = [];
        };
    
        ScopedSocket.prototype.removeAllListeners = function () {
            var i;
    
            for (i = 0; i < this.listeners.length; i++) {
                var details = this.listeners[i];
                this.socket.removeListener(details.event, details.fn);
            }
    
            for (i = 0; i < this.childSockets.length; i++) {
                this.childSockets[i].removeAllListeners();
            }
        };
    
        ScopedSocket.prototype.on = function (event, callback) {
            var socket = this.socket;
            var $rootScope = this.$rootScope;
    
            this.listeners.push({event: event, fn: callback});
    
            socket.on(event, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        };
    
        ScopedSocket.prototype.emit = function (event, data, callback) {
            var socket = this.socket;
            var $rootScope = this.$rootScope;
    
            socket.emit(event, angular.fromJson(angular.toJson(data)), function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            });
        };
    
        ScopedSocket.prototype.of = function (channel) {
            var childSocket = new ScopedSocket(this.socket.of(channel), this.$rootScope);
    
            this.childSockets.push(childSocket);
    
            return childSocket;
        };
    
    
        app.factory('Socket', ['$rootScope', function ($rootScope) {
            var socket = $rootScope.socket;
    
            return function(scope) {
                var scopedSocket = new ScopedSocket(socket, $rootScope);
                scope.$on('$destroy', function() {
                    scopedSocket.removeAllListeners();
                });
                return scopedSocket;
            };
        }]);
    })(window, window.app);
    
    0 讨论(0)
提交回复
热议问题