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 will add a space in an input box. In this example there are several events for the same key, but only one is fired at a time.

Is there a general (or specific for Javascript) method or way of programming to add events to a certain key, so they are only executed under certain circumstances?

Of course it can be done like this:

var inGame = true|false;
var inConfirmationBox = true|false;

function spaceBarHandler(){
    if(inGame){ /*shoot*/}
    else if(inConfirmationBox){ /*remove box*/}

document.onkeydown = function(){ /* call space bar handler if space bar was pressed */ };

But this is a very confusing way of programming, since specific actions are mixed together in a space bar handler function, which makes maintenance hard.

What is the best way to handle multiple events for one key, such that these events are only fired under certain circumstances?

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 actually

function spaceBarHandler() {
  var state = spaceBarHandler.state;
  var actions = spaceBarHandler.actions;

    // execute function if exists
    if (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.