I want to use socket.io in AngularJS.
I found the following factory:
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
and it is used in the controller like:
function MyCtrl($scope, socket) {
socket.on('message', function(data) {
...
});
};
the problem is that each time the controller is visited another listener is added, so when a message is received it is handled multiple times.
what can be a better strategy to integrate socket.io with AngularJS ?
EDIT: I know that I can return nothing in the factory and do the listening there, then use $rootScope.$broadcast and $scope.$on in the controllers, but it doesn’t look like a good solution.
EDIT2: added to the factory
init: function() {
socket.removeAllListeners();
}
and call it at the beginning of each controller that use socket.io.
still doesn’t feel like the best solution.
Remove the socket listeners whenever the controller is destroyed.
You will need to bind the
$destroyevent like this:For more information check the angularjs documentation.