Created
August 1, 2019 20:21
-
-
Save N8python/00f2fb3fa91c33f1cb6f3d941165b4ab to your computer and use it in GitHub Desktop.
Keybindr - A small and easy way to bind callbacks to keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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