Improve this AngularJS factory to use with socket.io

后端 未结 13 1529
你的背包
你的背包 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 different ways but nothing worked as expected. In my app I'm using a socket factory in both the MainController and a GameController. When the user switches to a different view I only want to remove the duplicates events generated by the GameController and leave the MainController running so I cannot use a removeAllListeners function. Instead I discovered a better way to just avoid creating duplicates inside my socket factory:

    app.factory('socket', function ($rootScope) {
      var socket = io.connect();
    
      function on(eventName, callback) {
        socket.on(eventName, function () {
          var args = arguments;
    
          $rootScope.$apply(function () {
            callback.apply(socket, args);
          });
        });
    
        // Remove duplicate listeners
        socket.removeListener(eventName, callback);
      }
    
      function emit(eventName, data, callback) {
        socket.emit(eventName, data, function () {
          var args = arguments;
    
          $rootScope.$apply(function () {
            if (callback) {
              callback.apply(socket, args);
            }
          });
        });
    
        // Remove duplicate listeners
        socket.removeListener(eventName, callback);
      }
    
      return {
        on: on,
        emit: emit
      };
    }
    

提交回复
热议问题