Skip to content

Instantly share code, notes, and snippets.

@N8python
Created August 1, 2019 20:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save N8python/00f2fb3fa91c33f1cb6f3d941165b4ab to your computer and use it in GitHub Desktop.
Save N8python/00f2fb3fa91c33f1cb6f3d941165b4ab to your computer and use it in GitHub Desktop.
Keybindr - A small and easy way to bind callbacks to keys.
window.keybindr = (() => {
// Declare set of keys that are pressed
const keys = new Set();
// Declare "associative array" of bindings to callback
const bindings = [];
function tokenizeKeys(keys){
// Get array of different keys from string
return keys.split("+");
}
window.addEventListener("keydown", ({key}) => {
// Register that the key is being pressed
keys.add(key);
// Check if all the keys in a binding are pressed, and if so, call the callbacks.
bindings.forEach(([binding, callback]) => {
if(binding.every(k => keys.has(k))) {
callback();
}
});
});
window.addEventListener("keyup", ({key}) => {
//Register that the key has been released
keys.delete(key);
});
return (keystr, binding) => {
// Create a new binding
bindings.push([tokenizeKeys(keystr), binding]);
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment