Pregunta

I'm trying to understand why this code execute an alert() 3 times:

$scope.logout = function () {
    $rootScope.auth.$logout();
    $rootScope.$on('$firebaseSimpleLogin:logout', function(event) {
       alert("Logged out"); // This appears 3 times.
    });
} 

But this just one:

$scope.logout = function () {
    $rootScope.auth.$logout();
    alert("Logged out"); // This JUST appears once.
}

I understand that the second approach is direct; first execute one line, then the other one. But what if $logout fails and the app displays that the operation was successful when it doesn't? Due to that possibility I'm using $firebaseSimpleLogin:logout event to handle the situation properly. Sadly, it isn't working as I imagined.

What could be wrong?

¿Fue útil?

Solución

It's difficult to say without seeing the rest of the application, but there is one error: in the first code sample, you're attaching another event listener every time $scope.logout is called--e.g., if you call it twice, the next time the event fires it'll alert twice. Click it again, and the next time the event fires, you'll get three alerts. You should move the registration of the event listener outside of the function call:

// put this anywhere that's only called once

app.run(function($rootScope) {
  $rootScope.$on("$firebaseSimpleLogin:logout", ...);
});

// elsewhere

$scope.logout = function() {
  $rootScope.auth.$logout();
};



// You could also unregister the function when you're done with it instead

app.controller("AuthController", function($scope, $rootScope) {
  var unregListener = $rootScope.$on("$firebaseSimpleLogin:logout", ...);
  $scope.$on("$destroy", unregListener);

  $scope.logout = function() { ... };
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top