PageRenderTime 25ms CodeModel.GetById 16ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/public/src/js/services/socket.js

https://github.com/barmatz/insight
JavaScript | 71 lines | 63 code | 8 blank | 0 comment | 5 complexity | 3eb602c6eaafb6639fade93fad25bbf4 MD5 | raw file
 1'use strict';
 2
 3var ScopedSocket = function(socket, $rootScope) {
 4  this.socket = socket;
 5  this.$rootScope = $rootScope;
 6  this.listeners = [];
 7};
 8
 9ScopedSocket.prototype.removeAllListeners = function(opts) {
10  if (!opts) opts = {};
11  for (var i = 0; i < this.listeners.length; i++) {
12    var details = this.listeners[i];
13    if (opts.skipConnect && details.event === 'connect') {
14      continue;
15    }
16    this.socket.removeListener(details.event, details.fn);
17  }
18  this.listeners = [];
19};
20
21ScopedSocket.prototype.on = function(event, callback) {
22  var socket = this.socket;
23  var $rootScope = this.$rootScope;
24
25  var wrapped_callback = function() {
26    var args = arguments;
27    $rootScope.$apply(function() {
28      callback.apply(socket, args);
29    });
30  };
31  socket.on(event, wrapped_callback);
32
33  this.listeners.push({
34    event: event,
35    fn: wrapped_callback
36  });
37};
38
39ScopedSocket.prototype.emit = function(event, data, callback) {
40  var socket = this.socket;
41  var $rootScope = this.$rootScope;
42
43  socket.emit(event, data, function() {
44    var args = arguments;
45    $rootScope.$apply(function() {
46      if (callback) {
47        callback.apply(socket, args);
48      }
49    });
50  });
51};
52
53angular.module('insight.socket').factory('getSocket',
54  function($rootScope) {
55    var socket = io.connect(null, {
56      'reconnect': true,
57      'reconnection delay': 500,
58    });
59    return function(scope) {
60      var scopedSocket = new ScopedSocket(socket, $rootScope);
61      scope.$on('$destroy', function() {
62        scopedSocket.removeAllListeners();
63      });
64      socket.on('connect', function() {
65        scopedSocket.removeAllListeners({
66          skipConnect: true
67        });
68      });
69      return scopedSocket;
70    };
71  });