In the following code, copied from ch 15 of Eloquent Javascript, how does pressed[codes[event.keyCode]]
end up as a boolean value? I just can’t figure out why you need the 'keyup'
event listener.
The idea is to make sure that 'keydown'
gets registered only once when it is being held down. I thought maybe the keyup event gets fired when you are holding the key down, as this MDN reference on the keydown
event suggests, but that resource says that functionality is discontinued.
var arrowCodes = {37: "left", 38: "up", 39: "right"}; function trackKeys(codes) { var pressed = Object.create(null); function handler(event) { if (codes.hasOwnProperty(event.keyCode)) { var down = event.type == "keydown"; pressed[codes[event.keyCode]] = down; event.preventDefault(); } } addEventListener("keydown", handler); addEventListener("keyup", handler); return pressed; }
Here is the text explaining this block of code. I don’t get it at all–where do true
and false
come from?
Note how the same handler function is used for both event types. It looks at the event object’s type property to determine whether the key state should be updated to true (“keydown”) or false (“keyup”).
Advertisement
Answer
var down = event.type == "keydown";
is exactly the same as
var down; if ( event.type == "keydown" ) { down = true; } else { down = false; }
If your question is about something else, then please indicate so.