Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Handle Multiple Key Events In Javascript?

Pressing space bar in game will make a character shoot, pressing space bar when a confirmation box is shown will make this box disappear and pressing space bar in a highscore form

Solution 1:

Functions are first-class objects in javascript, which makes them really powerful. Because of this, your problem can be solved very elegantly.

// the whole thing can be encapsulated // into an object actuallyfunctionspaceBarHandler() {
  var state = spaceBarHandler.state;
  var actions = spaceBarHandler.actions;

    // execute function if existsif (actions[state]) {
      actions[state]();
    }
}

// spaceBar actions
spaceBarHandler.actions = {
  shoot: function() {
    // bang bang
  },
  removeBox: function() {
    // do it...
  }
};

// change current state from outside// we are in the game
spaceBarHandler.state = "shoot";

// change current state from outside// confirmation box is shown 
spaceBarHandler.state = "removeBox";

All these cases will be handled by one function. If you want to extend with another case, you just add another function to the actions object. Notice how the whole thing is encapsulated into one object.

Solution 2:

you could instead add and remove the event listener as needed.

let's assume you're using a javascript framework (if you're not, then you probably should be considering the amount of JS code involved in a game like this)

using PrototypeJS:

when game starts,

document.observe("keydown",shootHandler());

when the message box is created,

functioncreateBox(text) {
    ...snip

    document.observe("keydown",closeBox());
    document.fire("game:pause");
}

and, for example

var paused = false;

functionshoothandler() {
   if (!paused) {
       alert("pew! pew!");
   }
}

functioncloseBox() {
    $('messagebox').remove();
    document.fire("game:unpaused");
    document.stopObserving("keydown",closeBox());
}

document.observe("game:paused", function() { paused = true;});
document.observe("game:unpaused", function() { paused = false;});
document.observe("game:over", function() { document.stopObserving("keydown",shootHandler());});

I haven't included the high score screen but the theory is the same.

As you can see, I also used custom events to notify the pause status. The same event could also be fire by a puase button in the interface, etc...

Solution 3:

Attach event listeners to individual elements instead of the entire document.

document.getElementById('highscore').onkeypress = function(keyEvent) {
      if (is_spacebar(keyEvent)) //Do something...
};

document.getElementById('game').onkeypress = function(keyEvent) {
      if (is_spacebar(keyEvent)) //Do something else...
};

This is a simplistic example. You will probably have to deal with event bubbling which can be controlled when using addEventListener() to attach functions to events. Given browser (IE) compatibility issues involving this, some JS library should be used to deal with events.

Solution 4:

There are a few ways, typically involving code-branching for IE's ‘special’ event model.

One way is to stop keypresses handled further down from bubbling up to the document key handler:

confirmationbox.onkeydown = function(event) {
    if (event === undefined) event = window.event;

    // do something with event.keyCodeif ('stopPropagation'inevent) // standards browsersevent.stopPropagation();
    elseif ('cancelBubble'inevent) // IE before version 9event.cancelBubble = true;
};

document.onkeydown = ... // will not be called for keydowns inside confirmationbox

Another way would be to check the event target element to see if it's in the box:

document.onkeydown = function(event) {
    if (event === undefined) event = window.event;
    var target = 'target'in event ? event.target : event.srcElement; // srcElement is for IE<9if (target === containerbox || isDescendantOf(target, containerbox) {
        // do containerbox stuff
    } else {
        // do other stuff
    }
};

functionisDescendantOf(element, ancestor) {
    while (element = element.parentNode)
        if (element === ancestor)
            returntrue;
    returnfalse;
}

Post a Comment for "What Is The Best Way To Handle Multiple Key Events In Javascript?"