Add keydown_util.js module.

This is a pretty thin abstraction to prevent having to put
magic numbers in code, doing the which/keyCode hack, and remembering
to all preventDefault.

Hopefully we'll expand it to handle things like shift/alt keys
for components that want their own keyboard handlers (vs. going
through hotkey.js).
This commit is contained in:
Steve Howell
2018-04-04 10:36:49 -04:00
committed by Tim Abbott
parent c06565d909
commit bd591424e2
5 changed files with 58 additions and 10 deletions

43
static/js/keydown_util.js Normal file
View File

@@ -0,0 +1,43 @@
var keydown_util = (function () {
var exports = {};
/*
See hotkey.js for handlers that are more app-wide.
*/
var keys = {
37: 'left_arrow',
38: 'up_arrow',
39: 'right_arrow',
40: 'down_arrow',
};
exports.handle = function (opts) {
opts.elem.keydown(function (e) {
var key = e.which || e.keyCode;
var key_name = keys[key];
if (!key_name) {
return;
}
if (!opts.handlers[key_name]) {
return;
}
var handled = opts.handlers[key_name]();
if (handled) {
e.preventDefault();
}
});
};
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = keydown_util;
}