Browse Source

close WebSocket when no longer needed

Davide Alberani 9 years ago
parent
commit
40db9b80ae
2 changed files with 23 additions and 8 deletions
  1. 6 0
      angular_app/js/controllers.js
  2. 17 8
      angular_app/js/services.js

+ 6 - 0
angular_app/js/controllers.js

@@ -74,6 +74,7 @@ eventManControllers.controller('EventDetailsCtrl', ['$scope', 'Event', 'Person',
 
             // Handle WebSocket connection used to update the list of persons.
             $scope.EventUpdates = EventUpdates;
+            $scope.EventUpdates.open();
             $scope.$watchCollection(function() {
                     return $scope.EventUpdates.data;
                 }, function(prev, old) {
@@ -197,6 +198,11 @@ eventManControllers.controller('EventDetailsCtrl', ['$scope', 'Event', 'Person',
         $scope.showMessage = function(cfg) {
             $scope.message.show(cfg);
         };
+
+        $scope.$on('$destroy', function() {
+            $log.debug('destroying controller');
+            $scope.EventUpdates && $scope.EventUpdates.close();
+        });
     }]
 );
 

+ 17 - 8
angular_app/js/services.js

@@ -137,20 +137,29 @@ eventManServices.factory('Setting', ['$resource',
 /* WebSocket collection used to update the list of persons of an Event. */
 eventManApp.factory('EventUpdates', ['$websocket', '$location', '$log',
     function($websocket, $location, $log) {
-        var proto = $location.protocol() == 'https' ? 'wss' : 'ws';
 
-        var dataStream = $websocket(proto + '://' + $location.host() + ':' + $location.port() +
-            '/ws/' + $location.path() + '/updates');
+        var dataStream = null;
 
         var data = {};
 
-        dataStream.onMessage(function(message) {
-            $log.debug('EventUpdates message received');
-            data.persons = angular.fromJson(message.data);
-        });
-
         var methods = {
             data: data,
+            close: function() {
+                $log.debug('close WebSocket connection');
+                dataStream.close();
+            },
+            open: function() {
+                $log.debug('open WebSocket connection');
+                dataStream && dataStream.close();
+                var proto = $location.protocol() == 'https' ? 'wss' : 'ws';
+                dataStream = $websocket(proto + '://' + $location.host() + ':' + $location.port() +
+                                    '/ws/' + $location.path() + '/updates');
+                dataStream.onMessage(function(message) {
+                    $log.debug('EventUpdates message received');
+                    data.persons = angular.fromJson(message.data);
+        });
+
+            }
         };
 
         return methods;