-1

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").

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Goodword
  • 1,565
  • 19
  • 27

3 Answers3

1

The truth values come from the line of code below:

var down = event.type == "keydown";

It sets down to be true if event.type is equal to "keydown", false otherwise, and can be read as:

var down = (event.type == "keydown");

or (far more verbose):

var down;
if (event.type == "keydown") {
    down = true;
} else {
    down = false;
}

The second line of the then goes on to store that truth value into the pressed array:

pressed[codes[event.keyCode]] = down;
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1
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.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • do new instances of all of those objects get created everytime I run that function? – Goodword Nov 06 '14 at 03:27
  • Your code creates a [`closure`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures). Object `pressed` is created when `trackKeys()` (outer function) is called and is available to `handler()` (inner function). Also see [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work). – PM 77-1 Nov 06 '14 at 15:02
0

The bool value comes from var down = event.type == "keydown";

precedence of RHS is always more, so first right expression event.type == "keydown" is evaluated and operator in this is "equal to" so the output of this will be based upon result of comparision expression which will be boolean value only.

KanhuP2012
  • 407
  • 3
  • 9