multiple listeners are added if the controller is entered more than once
bsphere opened this issue · 3 comments
for example, if a controller that uses the socket.io factory is attached to /home, each time /home is visited a socket.on listener is set.
when an event is emitted to the controller it is received multiple times
Yep, this is an issue. You can listen to $scope.$on('$destroy', ...)
. See: http://docs.angularjs.org/api/ng.$rootScope.Scope#Events
I'll try to update the example/blog post with more info when I get a chance.
hi how do we use $scope.$on('$destroy', ...) code to prevent the multiple event emitted problem?
actually thats what i did:
in my controller:
$scope.$on('$destroy', function (event) {
//socket.removeAllListeners();
socket.removeAllListeners();
//console.log('destroy triggered!');
});
And my socket factory is now updated to this:
app.factory('socket', function ($rootScope) {
var socket = io.connect('http://dils.biz:3006');
return {
removeAllListeners: function (eventName, callback) {
socket.removeAllListeners();
},
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);
}
});
})
}
};
});
The service is now implemented in a separate repo.
Please continue this discussion here: btford/angular-socket-io#3