Consider something like this:
const keyAction = {
a() {
console.log("You've pressed 'a'");
},
b() {
console.log("You've pressed 'b'");
},
c() {
console.log("You've pressed 'c'");
}
}
document.addEventListener('keydown', e => keyAction[e.key]());
Is this a bad practice? Are there any reason to not do it this way?
It's a popular practice actually, as some people tend to use objects to simulate namespaces from other languages. I think there's nothing bad with it, as long as you understand the traps that this approach may set. For example you should keep in mind what happens to this when you pass these functions as parameters (look at the example below):
const store = {
a() {
this.b();
},
b() {
console.log("It works!");
}
}
store.a(); // Logs "It works"
setTimeout(store.a, 10) // Error: this.b is not a function
Also, as noted by @Nick Ovchinnikov, in your specific example there is one other pitfall. You should make sure, that whenever a button is pressed, the environment will not try to invoke a function which doesn't exist - otherwise you might encounter an error. So eventually your handler binding should look somewhat like this:
document.addEventListener('keydown', e => {
if (typeof keyAction[e.key] === 'function') {
keyAction[e.key]();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With