vanillajs-deck/js/keyhandler.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-11-24 00:02:31 +00:00
// @ts-check
2019-11-23 20:20:09 +00:00
2019-11-24 00:02:31 +00:00
import { Navigator } from "./navigator.js"
/**
* Custom element to handle key press
*/
export class KeyHandler extends HTMLElement {
/**
* Create a key handler instance
*/
2019-11-23 20:20:09 +00:00
constructor() {
super();
2019-11-24 00:02:31 +00:00
/**
* The related Navigator element
* @type {Navigator}
*/
2019-11-23 20:20:09 +00:00
this._deck = null;
}
2019-11-24 00:02:31 +00:00
/**
* Gets the attributes being watched
* @returns {string[]} The attributes to watch
*/
2019-11-23 20:20:09 +00:00
static get observedAttributes() {
return ["deck"];
}
2019-11-24 00:02:31 +00:00
/**
* Called when attributes change
* @param {string} attrName The attribute that changed
* @param {string} oldVal The old value
* @param {string} newVal The new value
*/
2019-11-23 20:20:09 +00:00
async attributeChangedCallback(attrName, oldVal, newVal) {
if (attrName === "deck") {
if (oldVal !== newVal) {
2019-11-24 00:02:31 +00:00
this._deck = /** @type {Navigator} */(document.getElementById(newVal));
2019-11-23 20:20:09 +00:00
this._deck.parentElement.addEventListener("keydown", key => {
if (key.keyCode == 39 || key.keyCode == 32) {
this._deck.next();
}
else if (key.keyCode == 37) {
this._deck.previous();
}
});
}
}
}
}
2019-11-24 00:02:31 +00:00
/**
* Registers the custom key-handler element
*/
2019-11-23 20:20:09 +00:00
export const registerKeyHandler = () => customElements.define('key-handler', KeyHandler);