close WebSocket when no longer needed

This commit is contained in:
Davide Alberani 2015-04-26 12:42:47 +02:00
parent 2283e8cde9
commit 40db9b80ae
2 changed files with 23 additions and 8 deletions

View file

@ -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();
});
}]
);

View file

@ -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;