-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
89 lines (78 loc) · 1.45 KB
/
index.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
87
88
89
/*!
*
* keys
*
* bind to a key map
*
* MIT
*
*/
/**
* Module dependencies.
*/
var emitter = require('emitter');
var prevent = require('prevent');
var stop = require('stop');
/**
* Creates key `map` handler.
*
* `map` is an object with keycode property names
* where their corresponding values are emitted
* on keyup/down events.
*
* @param {Object} map
* @return {Object}
* @api public
*/
module.exports = function(map){
var pressed = {};
var keys = emitter({});
keys.onkeydown = on('keydown');
keys.onkeyup = on('keyup');
on.keydown = onkeydown;
on.keyup = onkeyup;
return keys;
/**
* Listener factory for key `state`.
*
* @param {String} state
* @return {Function}
* @api private
*/
function on(state){
return function(ev){
var key = map[ev.which];
if (key) {
stop(ev);
prevent(ev);
on[state](ev, key);
return false;
}
};
}
/**
* Keydown handler.
*
* @param {Event} event
* @param {Mixed} key
* @api private
*/
function onkeydown(event, key){
if (pressed[key]) return;
pressed[key] = true;
keys.emit('keydown', event, key);
keys.emit('change', event, key, 'down');
}
/**
* Keyup handler.
*
* @param {Event} event
* @param {Mixed} key
* @api private
*/
function onkeyup(event, key){
pressed[key] = false;
keys.emit('keyup', event, key);
keys.emit('change', event, key, 'up');
}
};