[英]Enable/Disable a EventListener
I'm building a Chess game on JS, and every pieces of the board are "clickable", I added an EventListener('click')
on them, I also added an EventListener('click')
after that to select where should the piece go.我正在 JS 上构建一个国际象棋游戏,棋盘的每一块都是“可点击的”,我在它们上面添加了一个 EventListener('click'
EventListener('click')
,之后我还在 select 中添加了一个EventListener('click')
件 go。
But I need to know if there's any kind of interrupter related to a EventListener
, in order to switch between an enabling an EventListener
and disabling it.但我需要知道是否存在与
EventListener
相关的任何类型的中断器,以便在启用EventListener
和禁用它之间切换。 For example, when an certain variable is true I'd only have white pieces clickable and black ones otherwise.例如,当某个变量为真时,我只有可点击的白色块和黑色块。
Instead of considering how to enable or disable listeners individually, I think it would be easier to have all clicks go through the same listener, and have that listener first check the board state to see whether a click on that location is permitted.与其考虑如何单独启用或禁用侦听器,我认为通过同一个侦听器让所有点击 go 并让该侦听器首先检查板 state 以查看是否允许单击该位置会更容易。 If not, return and don't do anything.
如果没有,请返回并且不做任何事情。 If so, continue.
如果是这样,请继续。
For example, you could have something like:例如,你可以有类似的东西:
const board = [
[ // row 1
{ // square 1A
piece: 'rook',
owner: 'white',
}
// ...
Then, inside the listener, navigate to the clicked square in the board
, and check whether the owner
corresponds to the current player or not.然后,在监听器内部,导航到
board
中被点击的方块,并检查owner
是否对应于当前玩家。
// inside listener:
// you will need to implement logic to get the row and column
// from a clicked button
const clickedSquare = board[i][j];
if (clickedSquare.owner !== currentPlayer) {
return;
}
// rest of function
When a turn ends, just toggle currentPlayer
from 'black'
to 'white'
or back again.当一个回合结束时,只需将
currentPlayer
从'black'
切换到'white'
或再次切换回来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.