Skip to content

Instantly share code, notes, and snippets.

@rafinskipg
Created December 24, 2013 13:37
Show Gist options
  • Save rafinskipg/8113476 to your computer and use it in GitHub Desktop.
Save rafinskipg/8113476 to your computer and use it in GitHub Desktop.
A thought on input js
"use strict";
var Input = {};
var functions = {
'mousedown' : [],
'mouseup': [],
'mousemove': [],
'keyup': [],
'keydown': [],
'mousewheel': []
}
//Suscribe
Input.on = function(name, fn){
if(!functions[name]){
return false;
}
functions[name].push(fn);
}
//Unsuscribe
Input.off = function(name, fn){
var index = functions[name].indexOf(fn);
functions[name].splice(index,1);
}
//Event listeners
document.documentElement.addEventListener("mousedown", mouseDown, false);
document.documentElement.addEventListener("mouseup", mouseUp, false);
document.documentElement.addEventListener("mousemove", mouseMove, false);
document.documentElement.addEventListener("keyup", keyUp, false);
document.documentElement.addEventListener("keydown", keyDown, false);
document.documentElement.addEventListener("mousewheel", mouseWheel, false);
document.documentElement.addEventListener("DOMMouseScroll", mouseWheel, false); // Firefox
//Triggers
function mouseWheel(e){
var index, mouseWheelDelta;
mouseWheelDelta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
e = e || window.event;
//Notify
for(index =0; index<functions['mousewheel'].length; index++){
functions['mousewheel'][index](mouseWheelDelta);
}
};
function keyDown(e){
var index,key;
e = e || window.event;
key = (typeof e.which === "undefined") ? e.keyCode : e.which;
//Notify
for(index =0; index<functions['keydown'].length; index++){
functions['keydown'][index](key);
}
};
function keyUp(e){
var index,key;
e = e || window.event;
key = (typeof e.which === "undefined") ? e.keyCode : e.which;
//Notify
for(index =0; index<functions['keyup'].length; index++){
functions['keyup'][index](key);
}
};
Input.touch = false;
Input.mouse = true;
Input.gamepad = false;
//suscribe
Input.on('click', myClickFunction);
Input.on('keyup', myKeyPressFunction);
Input.on('swipe', mySwipeFunction);
Input.on('gamepadKey', myGamePadKeyPressFunction);
//Unsuscribe
Input.off('click', myClickFunction);
function myKeyPressFunction(key){
//Swithc case key and do functionality
switch(key){
case "w":
//_---
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment