简体   繁体   中英

window.onunload event wont fire inside AngularJS controller

I have the following command inside an AngularJS controller

window.onunload = function () {
        connection.invoke("RemoveUser", playerName);
}

It's weired because I have a pure JS where this statement works well, so outsite an angularJS controller when I close the tab or the window, it fires and do its job, but when I put this inside a controller, it doesn't fire. Any ideas?

Full script bellow

 angular.module("mathGameApp", []).controller("mathGameCtrl", function ($scope) {
            // Current player name
            $scope.playerName;
            $scope.welcomeIsVisible = true;
            $scope.gameAreaIsVisible = false;
            $scope.countdownIsVisible = false;

            // Create connection
            const connection = new signalR.HubConnectionBuilder()
                .withUrl("/MathGame")
                .configureLogging(signalR.LogLevel.Information)
                .build();

            // Get math challenge
            connection.on("GetChallenge", data => {
                // Bind challenge
                $scope.expression = data.expression + " = " + data.possibleResult;
                $scope.$apply();
            });


            // Receive and bind score
            connection.on("ReceiveScore", data => {
                $scope.score = data;
                $scope.$apply();
            });

            // Rise alert
            connection.on("RiseAlert", data => {
                alert(data);
            })

            // Get status that the player was added to game room
            connection.on("AddedToGameRoom", data => {
                $scope.welcomeIsVisible = false;
                $scope.gameAreaIsVisible = true;
                $scope.$apply();
            })

            connection.on("ChallengeFinished", data => {
                $scope.counter = 5;
                $scope.countdownIsVisible = true;
                $scope.$apply();

                let interval = setInterval(function () {
                    if ($scope.counter == 0) {
                        $scope.countdownIsVisible = false;
                        $scope.buttonIsDisabled = false;
                        $scope.$apply();
                        clearInterval(interval);
                        connection.invoke("RefreshChallenge");
                    }
                    $scope.counter--;
                    $scope.$apply();
                }, 1000);

            })

            // rise answer Correct/Wrong
            connection.on("RiseAnswer", data => {

                $scope.buttonIsDisabled = true;
                $scope.expression = data;
                $scope.$apply();
                console.log($scope.buttonsDisabled);
                console.log($scope.expression);
            })

            // Request the user to be added to game room
            $scope.enterGame = function (playerName) {
                connection.invoke("EnterGame", playerName);
            }


            $scope.answerQuestion = function (playerName, answer) {
                connection.invoke("AnswerQuestion", {
                    "playerName": playerName, "isCorrect": answer
                });
            }


            // Open connection
            connection.start().then(() => {

            }).catch((err) => {
                alert(err.toString())
            });


            window.onunload = function () {
                connection.invoke("RemoveUser", playerName);
            }


        })

Controllers should use the $onDestroy Life-Cycle Hook to release external resources.

app.controller("mathGameCtrl", function ($scope) {
    ̶w̶i̶n̶d̶o̶w̶.̶o̶n̶u̶n̶l̶o̶a̶d̶ ̶=̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶)̶ ̶{̶ 
    this.$onDestroy = function () {
        connection.invoke("RemoveUser", playerName);
    }

})

For more information, see AngularJS $compile Service API Reference - Life-Cyle hooks .


Update

You can and should handle the 'unload' event through window.addEventListener() . It allows adding more than a single handler for an event. This is particularly useful for AJAX libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries/extensions.

For more information, see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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