I write code to JavaScript. I need to handle multiple keys when pressed. The result of such a code.
var key = event.keyCode;
if (key === 39 {
//some code
}
if (key === 40) {
//some code
}
if (key === 38) {
//some code
}
if (key === 13) {
//some code
}
I do not like this method, if there is another beautiful way? in the style of object-oriented programming? Thanks
JavaScript is not an object oriented language per se.
What you could do is make a mapped object.
const obj = {
"39" : () => { //do this },
"40" : () => { //do this },
"38" : () => { //do this },
"13" : () => { //do this }
}
Then, when your event code comes in... use const whatever = obj[event.keyCode]();
I also believe that some form of destructuring can make this even fancier, but I'd have to brush up on it.
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