gpt4 book ai didi

javascript - 为什么 $firebaseSimpleLogin :logout event execute an alert() more than once?

转载 作者:行者123 更新时间:2023-12-03 12:39:28 24 4
gpt4 key购买 nike

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

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

但这只是一个:

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

关于javascript - 为什么 $firebaseSimpleLogin :logout event execute an alert() more than once?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com