简体   繁体   English

为什么$ firebaseSimpleLogin:logout事件多次执行alert()?

[英]Why $firebaseSimpleLogin:logout event execute an alert() more than once?

I'm trying to understand why this code execute an alert() 3 times: 我试图理解为什么此代码执行一次alert()3次:

$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? 但是,如果$ logout失败并且应用程序显示操作成功则显示失败,该怎么办? Due to that possibility I'm using $firebaseSimpleLogin:logout event to handle the situation properly. 由于这种可能性,我正在使用$firebaseSimpleLogin:logout事件来正确处理这种情况。 Sadly, it isn't working as I imagined. 可悲的是,它没有像我想象的那样工作。

What could be wrong? 有什么事吗

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--eg, if you call it twice, the next time the event fires it'll alert twice. 不看应用程序的其余部分就很难说,但是有一个错误:在第一个代码示例中,每次调用$scope.logout时,您都将附加另一个事件侦听器-例如,如果您两次调用它,下次事件触发时,它将发出两次警报。 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() { ... };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM