dimanche 20 octobre 2019

How to handle keypress event properly in Ember js 3.13

I'm new to Ember & I want to catch a global key press event and handle it in my component.

After a lot of web crawling I did it the old fashion way with global window.onkeydown = this.handleKeyPress & at the handleKeyPress function i did some code and call this.movePlayerInDirection but now my 'this' is the window.

onKeyPress(e, comp) { let keyCode = e.keyCode;

    if (keyCode === KEY_LEFT ||
        keyCode === KEY_UP ||
        keyCode === KEY_RIGHT ||
        keyCode === KEY_DOWN) {
        let direction;

        switch(e.keyCode) {
            case KEY_LEFT:
                direction = {x: -1, y: 0}
                break;
            case KEY_RIGHT:
                direction = {x: 1, y: 0}
                break;
            case KEY_UP:
                direction = {x: 0, y: -1}
                break;
            case KEY_DOWN:
                direction = {x: 0, y: 1}
                break;
        }
        this.movePlayerInDirection(direction);
    }
}
  1. Is this the best way to catch this event? (the ember way)

  2. How do i reach the component functions from the window scope?




Aucun commentaire:

Enregistrer un commentaire