Created
August 19, 2018 06:53
-
-
Save davalapar/bf883924a449ae1a9b242263208fd95d to your computer and use it in GitHub Desktop.
Keylock.js
This file contains 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
/* eslint-disable no-undef */ | |
// http://keycode.info | |
class Keylock { | |
constructor(key) { | |
this.keyCode = key.charCodeAt(0); | |
this.isDown = false; | |
this.isUp = true; | |
this.onPress = undefined; | |
this.onRelease = undefined; | |
window.addEventListener( | |
'keydown', this.downHandler.bind(this), false, | |
); | |
window.addEventListener( | |
'keyup', this.upHandler.bind(this), false, | |
); | |
} | |
downHandler(event) { | |
if (event.keyCode === this.keyCode) { | |
if (this.isUp === true && typeof this.onPress === 'function') { | |
this.onPress(); | |
} | |
this.isDown = true; | |
this.isUp = false; | |
} | |
event.preventDefault(); | |
} | |
upHandler(event) { | |
if (event.keyCode === this.keyCode) { | |
if (this.isDown === true && typeof this.onRelease === 'function') { | |
this.onRelease(); | |
} | |
this.isDown = false; | |
this.isUp = true; | |
} | |
event.preventDefault(); | |
} | |
setOnPress(parameter) { | |
if (typeof parameter === 'function') { | |
this.onPress = parameter; | |
} | |
return this; | |
} | |
setOnRelease(parameter) { | |
if (typeof parameter === 'function') { | |
this.onRelease = parameter; | |
} | |
return this; | |
} | |
} | |
export default Keylock; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment