Javascript 为什么$firebaseSimpleLogin:logout事件会多次执行警报()?

Javascript 为什么$firebaseSimpleLogin:logout事件会多次执行警报()?,javascript,angularjs,firebase,firebase-security,Javascript,Angularjs,Firebase,Firebase Security,我试图理解为什么这段代码会执行警报()3次: 但这只是一个: $scope.logout = function () { $rootScope.auth.$logout(); alert("Logged out"); // This JUST appears once. } 我知道第二种方法是直接的;首先执行一行,然后执行另一行。但是,如果$logout失败,应用程序显示操作成功,而实际操作失败,该怎么办?由于这种可能性,我正在使用$firebaseSimpleLogin:lo

我试图理解为什么这段代码会执行警报()3次:

但这只是一个:

$scope.logout = function () {
    $rootScope.auth.$logout();
    alert("Logged out"); // This JUST appears once.
}
我知道第二种方法是直接的;首先执行一行,然后执行另一行。但是,如果$logout失败,应用程序显示操作成功,而实际操作失败,该怎么办?由于这种可能性,我正在使用
$firebaseSimpleLogin:logout
事件来正确处理这种情况。可悲的是,它没有像我想象的那样工作


有什么不对劲吗

很难说没有看到应用程序的其余部分,但是有一个错误:在第一个代码示例中,每次调用
$scope.logout
时,您都会附加另一个事件侦听器,例如,如果您调用两次,下次事件触发时,它会发出两次警报。再次单击它,下次触发事件时,您将收到三个警报。您应该将事件侦听器的注册移到函数调用之外:

// 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() { ... };
});

谢谢@BrandonTilley!我听从了你的建议,现在一切都很顺利。另外,你的回答帮助我理解了我应用程序中的另一个问题;我不知道在函数中附加一个事件侦听器是不好的。@有时这样做很有用有时你想附加多个侦听器,但你必须小心不要附加重复的侦听器。
// 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() { ... };
});