Improve this AngularJS factory to use with socket.io

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

    I am doing this to avoid duplicated listeners and works pretty well.

     on: function (eventName, callback) {
      //avoid duplicated listeners
      if (listeners[eventName] != undefined) return;
    
      socket.on(eventName, function () {
         var args = arguments;
         $rootScope.$apply(function () {
            callback.apply(socket, args);
         });
         listeners[eventName] = true;
      });
    },
    

提交回复
热议问题