1

I've been learning CreateJS, and when I go to this part that has to add an eventlistener, it just won't work. The messages I put in addKey() and removeKey() just don't show up.

function startGame() {
    window.addEventListener("keydown", addKey, false);
    window.addEventListener("keyup", removeKey, false);
    console.log("added listeners");

    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", tick);
}

function addKey(e) {
    console.log("RUN!");
    e = !e ? window.event : e;
    var index = KEYS_ALLOWED.indexOf(e.keyCode);
    if (true) {
        keysPressed.push(e.keyCode);
    }
}

function removeKey(e) {
    console.log("RUN!");
    e = !e ? window.event : e;
    var index = keysPressed.indexOf(e.keyCode);
    if (index > -1) {
        keysPressed.splice(index, 1);
    }
}

EDIT: Yes, the startGame is getting called. I put it in this, which is called when the body loads:

function init() {
        canvas = document.getElementById("canvas");
        stage = new createjs.Stage(canvas);
        console.log("created stage");

        createAssets();
        placeAssets();
        startGame();
}

By the way, it seems to work if I put

document.addEventListener

instead of

window.addEventListener

though the book I was using used the latter. Is there a reason for that, and will it affect me negatively if I just press on with it using the former?

Lanny
  • 11,244
  • 1
  • 22
  • 30

1 Answers1

0

There should be no specific reason to prefer window.addEventListener over document.addEventListener or vice versa in your case since both should produce the same event object (e in your case) and did so when I tested your code.

Using the answer here for reference: Difference between document.addEventListener and window.addEventListener?

You will notice that "The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either". So it should not affect you negatively if you continue by using document.addEventListener.

Please note that(also from the linked question): "Since 'click' event is available in both document and window and if we register event on both document and window then the click handler of document fire first then window. so for this point of view choice of document is better." In short, performance-wise, it would be slightly better to go with document.addEventListener.

starter
  • 1
  • 2