如何在 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,而不会让这些动作发生碰撞(

最新更新