API Docs for: 0.0.1
Show:

File: src/link/Keyboard.js

/**
 * @author Vsevolod Strukchinsky @floatdrop
 */

/**
Keyboard class handles keys.

@example
	// LINK.Key is a global LINK.Keyboard manager class

	// Bind keys
	LINK.Key.W.press(moveUpCallback);
	LINK.Key.S.press(moveDownCallback);
	LINK.Key.A.press(moveLeftCallback);
	LINK.Key.D.press(moveRightCallback);

	// Fire all pressed keys
	Object.keys(LINK.Key.pressed).forEach(function (code) { 
		LINK.Key.pressed[code].press(); 
	});


@class Keyboard
@constructor
**/
LINK.Keyboard = function () {
	var self = this;
	this.pressed = {};
	this.callbacks = {};

	Object.keys(this.Codes).forEach(function (keyName) {
		self[keyName] = {
			press: function (callback) {
				self.callbacks[keyName] = callback;
				return self;
			}
		};
		Object.defineProperty(self.pressed, LINK.Keyboard.prototype.Codes[keyName], {
			configurable: true,
			get: function () {
				return {
					press: function () {
						self.callbacks[keyName](keyName);
					}
				};
			}
		});
	});

	document.addEventListener('keydown', this.onKeyDown.bind(this), false);
	document.addEventListener('keyup', this.onKeyUp.bind(this), false);
};

LINK.Keyboard.constructor = LINK.Keyboard;
LINK.Keyboard.prototype = Object.create(Object.prototype);

LINK.Keyboard.prototype.onKeyDown = function (e, override) {
	return this.modifyKey(e, override || e.keyCode || e.which, true);
};

LINK.Keyboard.prototype.onKeyUp = function (e, override) {
	return this.modifyKey(e, override || e.keyCode || e.which, false);
};

LINK.Keyboard.prototype.modifyKey = function (e, key, val) {
	Object.defineProperty(this.pressed, key, {
		enumerable: val
	});
	return true;
};

/**
 * Maps names of keys to theirs codes
 * @property Codes
 */
LINK.Keyboard.prototype.Codes = {
	'Backspace': 8,
	'Tab': 9,
	'Enter': 13,
	'Shift': 16,
	'Ctrl': 17,
	'Alt': 18,
	'Pause': 19,
	'Capslock': 20,
	'Esc': 27,
	'Pageup': 33,
	'Pagedown': 34,
	'End': 35,
	'Home': 36,
	'Leftarrow': 37,
	'Uparrow': 38,
	'Rightarrow': 39,
	'Downarrow': 40,
	'Insert': 45,
	'Delete': 46,
	'0': 48,
	'1': 49,
	'2': 50,
	'3': 51,
	'4': 52,
	'5': 53,
	'6': 54,
	'7': 55,
	'8': 56,
	'9': 57,
	'A': 65,
	'B': 66,
	'C': 67,
	'D': 68,
	'E': 69,
	'F': 70,
	'G': 71,
	'H': 72,
	'I': 73,
	'J': 74,
	'K': 75,
	'L': 76,
	'M': 77,
	'N': 78,
	'O': 79,
	'P': 80,
	'Q': 81,
	'R': 82,
	'S': 83,
	'T': 84,
	'U': 85,
	'V': 86,
	'W': 87,
	'X': 88,
	'Y': 89,
	'Z': 90,
	'0numpad': 96,
	'1numpad': 97,
	'2numpad': 98,
	'3numpad': 99,
	'4numpad': 100,
	'5numpad': 101,
	'6numpad': 102,
	'7numpad': 103,
	'8numpad': 104,
	'9numpad': 105,
	'Multiply': 106,
	'Plus': 107,
	'Minut': 109,
	'Dot': 110,
	'Slash1': 111,
	'F1': 112,
	'F2': 113,
	'F3': 114,
	'F4': 115,
	'F5': 116,
	'F6': 117,
	'F7': 118,
	'F8': 119,
	'F9': 120,
	'F10': 121,
	'F11': 122,
	'F12': 123,
	'equal': 187,
	'Coma': 188,
	'Slash': 191,
	'Backslash': 220
};

LINK.Key = new LINK.Keyboard();