js/Mobilizing/input/Keyboard.js
import Component from '../core/Component';
/**
* Fired when a new keydown event occures
* @event keydown
*/
const EVT_KEY_DOWN = "keydown";
/**
* Fired when a new keypressed event occures
* @event keypressed
*/
const EVT_KEY_PRESS = "keypress";
/**
* Fired when a new keyup event occures
* @event keyup
*/
const EVT_KEY_UP = "keyup";
/**
* Simple mapping from HTLM keyboard events toward Mobilizing.js. Not of a big interest for now...
*
* @param {Object} params Config parameters
* @param {Window} [params.target=window] The DOM element this instance is attached to
*/
export default class Keyboard extends Component {
/**
* @param {Object} params Parameters object, given by the constructor.
* @param {DOMElement} params.target The DOM element that will be used to attach keyboard events on
*/
constructor({
target = window,
} = {}) {
super(...arguments);
this.target = target;
}
on() {
super.on();
this.target.addEventListener("keydown", (event) => this.onKeyDown(event));
this.target.addEventListener("keypress", (event) => this.onKeyPress(event));
this.target.addEventListener("keyup", (event) => this.onKeyUp(event));
}
off() {
super.off();
this.target.removeEventListener("keydown", (event) => this.onKeyDown(event));
this.target.removeEventListener("keypress", (event) => this.onKeyPress(event));
this.target.removeEventListener("keyup", (event) => this.onKeyUp(event));
}
setup() {
if (!this._setupDone) {
//note: on window, keypress events are continously called, like keydown. It's not the case of html element
//we reproduce this behavior here.
this._isPressed = false;
// this._keyDownCode;
super.setup();
}
}
update() {
}
/**
* Fast way to verify in an update loop if a specific key is currently down
*
* @method getKeyIsDown
* @param {Object} key
* @return {Boolean} is down or not
*/
getKeyIsDown(key) {
return (this._keyDownCode === key.toLowerCase());
}
/**
* Forward the keydown event
*
* @private
* @method onKeyDown
* @param {Object} event
*/
onKeyDown(event) {
this._keyDownCode = String.fromCharCode(event.keyCode).toLowerCase();
this.events.trigger(EVT_KEY_DOWN, event);
//event.preventDefault();
}
/**
* Forward the keypress event
*
* @private
* @method onKeyPress
* @param {Object} event
*/
onKeyPress(event) {
this._keyDownCode = String.fromCharCode(event.keyCode).toLowerCase();
this.events.trigger(EVT_KEY_PRESS, event);
this._isPressed = true;
event.preventDefault();
}
/**
* Forward the keyup event
*
* @private
* @method onKeyUp
* @param {Object} event
*/
onKeyUp(event) {
this._keyDownCode = undefined;
this._isPressed = false;
this.events.trigger(EVT_KEY_UP, event);
}
}