-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventHandler.js
86 lines (73 loc) · 2.02 KB
/
eventHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function EventHandler() {
this.events = {};
this.listen();
}
EventHandler.prototype.addHandler = function(event, callback) {
this.events[event] = callback;
};
EventHandler.prototype.removeHandler = function(event) {
this.events[event] = null;
};
EventHandler.prototype.handle = function(event, data) {
var callback = this.events[event];
if (callback) callback(data);
};
EventHandler.prototype.listen = function() {
var self = this;
var canvas = document.querySelector('canvas');
canvas.onmousedown = function(event) {
var position = { x: event.clientX, y: event.clientY };
self.handle('mousedown', position);
};
window.addEventListener('keydown', function(event) {
event.preventDefault();
var map = {
37: 'left',
65: 'left',
38: 'up',
87: 'up',
39: 'right',
68: 'right',
40: 'down',
83: 'down',
82: 'undo'
};
var mapped = map[event.keyCode];
if (mapped === undefined) return;
if (mapped == 'undo') self.handle('undo');
else self.handle('move', mapped);
}, false);
var restartBtn = document.getElementById('restartBtn');
restartBtn.onclick = function(event) {
event.preventDefault();
self.handle('restart');
};
var undoBtn = document.getElementById('undoBtn');
undoBtn.onclick = function(event) {
event.preventDefault();
self.handle('undo');
};
var nextBtn = document.getElementById('nextBtn');
nextBtn.onclick = function() {
self.handle('next');
};
var nameInput = document.getElementById('nameInput');
var addBtn = document.getElementById('addBtn');
nameInput.onkeyup = function () {
if (nameInput.value.length > 0) {
addBtn.disabled = false;
} else {
addBtn.disabled = true;
}
};
addBtn.onclick = function() {
var value = nameInput.value;
self.handle('addScore', value);
addBtn.disabled = 'true';
nameInput.value = '';
};
var newGameBtn = document.getElementById('newGameBtn');
newGameBtn.onclick = function() {
self.handle('newGame');
};
};