Last active
December 17, 2015 13:49
-
-
Save ehgoodenough/5620109 to your computer and use it in GitHub Desktop.
As discussed over at www.stackoverflow.com/questions/14893988, binding the functionality of a keystroke to an action instead of a state will establish noninterrupting events while still preserving individual keystrokes.
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
var kbdin = | |
{ | |
downbinded: new Object(), | |
upbinded: new Object(), | |
stroked: new Object(), | |
downbindKeystroke: function(keyCode, functionality) | |
{ | |
this.downbinded[keyCode] = functionality; | |
}, | |
upbindKeystroke: function(keyCode, functionality) | |
{ | |
this.upbinded[keyCode] = functionality; | |
}, | |
isDownbinded: function(keyCode) | |
{ | |
return this.downbinded[keyCode]; | |
}, | |
isUpbinded: function(keyCode) | |
{ | |
return this.upbinded[keyCode]; | |
}, | |
isStroked: function(keyCode) | |
{ | |
return this.stroked[keyCode]; | |
}, | |
onDownstroke: function(event) | |
{ | |
var keyCode = event.keyCode; | |
if(!this.isStroked(keyCode)) | |
{ | |
this.stroked[keyCode] = 1; | |
if(this.isDownbinded(keyCode)) | |
{ | |
this.downbinded[keyCode](); | |
} | |
} | |
if(this.isDownbinded(keyCode)) | |
{ | |
event.preventDefault(); | |
} | |
}, | |
onUpstroke: function(event) | |
{ | |
var keyCode = event.keyCode; | |
delete this.stroked[keyCode]; | |
if(this.isUpbinded(keyCode)) | |
{ | |
this.upbinded[keyCode](); | |
event.preventDefault(); | |
} | |
}, | |
handleKeystrokes: function() | |
{ | |
for(var keyCode in this.downbinded) | |
{ | |
if(this.isStroked(keyCode) > this.keyDelay) | |
{ | |
this.downbinded[keyCode](); | |
} | |
} | |
for(var keyCode in this.stroked) | |
{ | |
this.stroked[keyCode]++; | |
} | |
}, | |
keyDelay: 5, | |
keyFrequency: 50 | |
} | |
window.addEventListener("keydown", function(event) {kbdin.onDownstroke(event);}, false); | |
window.addEventListener("keyup", function(event) {kbdin.onUpstroke(event);}, false); | |
window.setInterval(function() {kbdin.handleKeystrokes();}, kbdin.keyFrequency); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment