Skip to content

Instantly share code, notes, and snippets.

@bradenbest
Last active February 28, 2024 09:08
Show Gist options
  • Save bradenbest/7251ca42af2991f234346baeabbf435b to your computer and use it in GitHub Desktop.
Save bradenbest/7251ca42af2991f234346baeabbf435b to your computer and use it in GitHub Desktop.
Input Helper Class
function Input(el){
var parent = el,
map = {},
intervals = {};
function ev_kdown(ev)
{
map[ev.key] = true;
ev.preventDefault();
return;
}
function ev_kup(ev)
{
map[ev.key] = false;
ev.preventDefault();
return;
}
function key_down(key)
{
return map[key];
}
function keys_down_array(array)
{
return typeof array.find( key => !key_down(key) ) === "undefined";
}
function keys_down_arguments(...args)
{
return keys_down_array(args);
}
function clear()
{
map = {};
}
function watch_loop(keylist, callback)
{
return function(){
if(keys_down_array(keylist))
callback();
}
}
function watch(name, callback, ...keylist)
{
intervals[name] = setInterval(watch_loop(keylist, callback), 1000/24);
}
function unwatch(name)
{
clearInterval(intervals[name]);
delete intervals[name];
}
function detach()
{
parent.removeEventListener("keydown", ev_kdown);
parent.removeEventListener("keyup", ev_kup);
}
function attach()
{
parent.addEventListener("keydown", ev_kdown);
parent.addEventListener("keyup", ev_kup);
}
function Input()
{
attach();
return {
key_down: key_down,
keys_down: keys_down_arguments,
watch: watch,
unwatch: unwatch,
clear: clear,
detach: detach
};
}
return Input();
}

Here is the interface reference:

Boolean  key_down (String key);
Returns `true` if `key` is down, false otherwise.

Boolean  keys_down (String key1, String key2, ...);
Returns `true` if all keys `key1 .. keyN` are down, false otherwise.

void     watch (String name, Function callback, String key1, String key2, ...);
Creates a "watchpoint" such that pressing all of `keyN` will trigger the callback

void     unwatch (String name);
Removes said watchpoint via its name

void     clear (void);
Wipes the "keys down" cache. Equivalent to `map = {}` above

void     detach (void);
Detaches the `ev_kdown` and `ev_kup` listeners from the parent element, making it possible to safely get rid of the instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment