Reputation: 2093
I'm currently building an AngularJS website with a game. Here I want to use the keyboard to resume/pause and control the game. The code I have to add the eventlistener is the following:
$window.addEventListener('keydown', function(e) {
if ($scope.gameState.playing) {
for (var control in controls) {
if (controls.LEFT.indexOf(e.keyCode) > -1) {
gameEngine.startLeft();
} else if (controls.RIGHT.indexOf(e.keyCode) > -1) {
gameEngine.startRight();
} else if (controls.POWERJUMP.indexOf(e.keyCode) > -1) {
gameEngine.powerJump();
} else if (controls.PAUSE.indexOf(e.keyCode) > -1) {
$scope.pauseGame();
}
}
}
});
The content of the function isn't very important, but my problem is that it gets called 7 times every time I press a key. The same is with keyup
. However fast or slow I press it.
var GameApp = angular.module('GameApp', []);
GameApp.controller('GameController', function($scope, $timeout, $window)
The above code is how I create the Angular app and controller with the $window argument.
I couldn't find a solution for this. I hope anyone knows why that's happening.
Upvotes: 0
Views: 205
Reputation: 7926
Wild guess: is the event handler registered 7 times?
To check do something like:
$window.addEventListener('keydown', function(e) {
if(e.iAmNotAlone) {
throw new Error('Oh dear!');
}
e.iAmNotAlone = true;
/* for control in control thingy goes here */
});
Are you setting this up in the singleton part of a service or in some sort of controller (which will be recreated every time and could explain this behaviour) ?
Upvotes: 1