在Javascript中处理多个关键事件的最佳方式是什么? [英] What is the best way to handle multiple key events in Javascript?

查看:116
本文介绍了在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.

是否有一般的(或特定于Javascript)的方法或方法编程将事件添加到某个键,所以它们只能在某些情况下执行?

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?

当然可以这样做:

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?

推荐答案

功能是javascript中的一流对象,这使它们非常强大。因此,您的问题可以非常优雅地解决。

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";

所有这些情况都将由一个功能处理。如果要扩展另一种情况,您只需向actions对象添加另一个函数即可。注意整个事情被封装到一个对象中。

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.

这篇关于在Javascript中处理多个关键事件的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆