Last active
December 16, 2017 06:11
-
-
Save ssajous/88ff50ab820f59f58b5ec807541675a9 to your computer and use it in GitHub Desktop.
ES6 module to handle the Konami code input in a browser.
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
const _code = "38384040373937396665"; | |
export default class CheatCode { | |
code = ''; | |
delay = 1500; | |
callbacks = []; | |
timeout = null; | |
constructor() { | |
this.handler = this.handler.bind(this); | |
this.dispatch = this.dispatch.bind(this); | |
document.addEventListener("keydown", this.handler, false); | |
} | |
handler(e) { | |
try { | |
clearTimeout(this.timeout); | |
} catch (error) { } | |
this.code = String(this.code + e.keyCode); | |
if (this.code === _code) { | |
this.dispatch("cheat code"); | |
} | |
this.timeout = setTimeout(() => { | |
clearTimeout(this.timeout); | |
this.code = ''; | |
}, this.delay); | |
} | |
listen(callback) { | |
if (typeof callback === "function") { | |
this.callbacks.push(callback); | |
} | |
return this; | |
} | |
dispatch() { | |
for (let i = this.callbacks.length; i--;) { | |
this.callbacks[i](); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactored to ES6 from https://github.com/ProperJS/KonamiCode