From 4de2a6636a4de682edc5c3bbd4d1f5e940e879a3 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Fri, 8 Jan 2016 12:18:40 +0100 Subject: InputHandler: prevent default for relavant keys --- src/app.ts | 12 +++++++++++- src/util.ts | 9 +++++++++ src/view/InputHandler.ts | 12 +++++++++++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index e47d41f..37aae93 100644 --- a/src/app.ts +++ b/src/app.ts @@ -11,6 +11,16 @@ import MapContext from './control/MapContext'; import MapData from './model/MapData'; import InputHandler from './view/InputHandler'; +import * as util from './util'; + + +var relevantKeys = [ + InputHandler.Up, + InputHandler.Right, + InputHandler.Down, + InputHandler.Left, +]; + var mapContext: MapContext; @@ -19,7 +29,7 @@ window.onload = () => { xhr.onload = function() { var mapDef = new MapData(JSON.parse(this.responseText)); - var inputHandler = new InputHandler(); + var inputHandler = new InputHandler(util.numberArrayToMap(relevantKeys)); mapContext = new MapContext(mapDef, inputHandler); } diff --git a/src/util.ts b/src/util.ts index 6ab90ce..ad2b482 100644 --- a/src/util.ts +++ b/src/util.ts @@ -11,3 +11,12 @@ export function mapPromises(promises: {[key: string]: Promise}): Promise<{ return Promise.all(p).then(() => ret); } + +export function numberArrayToMap(arr: number[]): {[key: number]: boolean} { + var ret: {[key: number]: boolean} = {}; + + for (let v of arr) + ret[v] = true; + + return ret; +} diff --git a/src/view/InputHandler.ts b/src/view/InputHandler.ts index 86d4ec6..d06bcf8 100644 --- a/src/view/InputHandler.ts +++ b/src/view/InputHandler.ts @@ -13,8 +13,13 @@ class InputHandler { this.listeners.forEach(l => l()); } - constructor() { + constructor(private relevantKeys: {[key: number]: boolean}) { window.addEventListener('keydown', (ev) => { + if (!relevantKeys[ev.keyCode]) + return; + + ev.preventDefault(); + if (!this.keys[ev.keyCode]) { this.keys[ev.keyCode] = true; this.callListeners(); @@ -22,6 +27,11 @@ class InputHandler { }); window.addEventListener('keyup', (ev) => { + if (!relevantKeys[ev.keyCode]) + return; + + ev.preventDefault(); + if (this.keys[ev.keyCode]) { delete this.keys[ev.keyCode]; this.callListeners(); -- cgit v1.2.3