如何在js中实现嵌套的事件监听器

How to implement nested event listeners in js

我正在构建一个文字冒险游戏,它接受用户输入并引导玩家沿着树状结构向下移动。我的想法是让一个主要事件监听器监听将开始游戏的提交操作。然后我根据初始响应继续添加另一个事件侦听器,但没有任何反应。

嵌套事件侦听器是否是处理这种情况的正确方法?

//prompts
const bed = 'Your lack of desire has lead you towards a life of bordeom and dread. [[GAME OVER]]'.split('');
const explore = 'As your eyes adjust to the early monning sun, you glance around the room. To your left, you notice a small, but sturdy bed side table. In front of you, a TV is broadcasting re-runs of the show "Friends". You also consider walking and exploring more of this strange room.What is your next inclination?'.split('')
const walkAroundRoom = 'Walking around the room seems like a good idea. After all, you tell yourself, "I should at least aquainte and introduce myself to this bewildering experience. After a bit of pondering and wandering, you look straight ahead and notice a bathroom. To your right, a window.'.split('')

submit.addEventListener('submit', () => {
  if (response('bed')) {
    go(bed)
  } else if (response('ex')) {
    go(explore)

    submit.addEventListener('submit',()=>{
      if(response('tv')){
        go(watchTV)
      } else if(response('walk')){
        go(walkAroundRoom)
      }
    })
  }
})

我会使用一个对象,它的键唯一地标识一组文本,值包含要显示的文本和每个可能的响应将指向的提示键。这样,您只需添加一个监听器:

const prompts = {
  wake: {
    text: 'You wake, enter "walk" or "explore"',
    responses: { walk: 'wake_walk', explore: 'wake_explore' }
  },
  wake_explore: {
    text: 'You explore after waking. Enter "walk" to walk',
    responses: { walk: 'wake_walk' }
  },
  wake_walk: {
    text: 'You walk. Enter "walk" to continue walking, or "sleep" to go back to sleep',
    responses: { walk: 'wake_walk', sleep: 'sleep' }
  },
  sleep: {
    text: 'You sleep.',
    responses: {}
  }
};

const [div, input, button, errors] = document.querySelectorAll('div, input, button');
let lastResponses;
const displayPrompt = ({ text, responses }) => {
  div.textContent = text;
  lastResponses = responses;
};
displayPrompt(prompts.wake);

button.addEventListener('click', () => {
  const nextPrompt = prompts[lastResponses[input.value]];
  if (nextPrompt) {
    displayPrompt(nextPrompt);
    errors.textContent = '';
  } else {
    errors.textContent = 'Action not possible now';
  }
  input.value = '';
});
<div></div>
<input>
<button>submit</button>
<div></div>

半永久性 lastResponses 用于保存最后一个响应对象,以便在不同情况下可以输入相同的操作,同时指向不同的 prompts 键。 (例如,您可以在起床后 walk,在街上也可以 walk,并且这些动作不会发生冲突)