What is the best way to handle multiple key events in Javascript?

前端 未结 4 2120
半阙折子戏
半阙折子戏 2021-02-08 11:24

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 fo

4条回答
  •  萌比男神i
    2021-02-08 11:49

    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]) {
          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.

提交回复
热议问题