Created
October 11, 2017 11:34
-
-
Save nathanchicken/d3f73dd97dceabbb29d1c65c63d0ec35 to your computer and use it in GitHub Desktop.
Helper to register keyboard events by named functions. Simple at the moment, could do with some more keywords.
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
(function(window, factory) { | |
var onKeyboard = factory(window, window.document); | |
window.onKeyboard = onKeyboard; | |
if(typeof module == 'object' && module.exports){ | |
module.exports = onKeyboard; | |
} | |
})(window, function(window, document) { | |
// var keycodes = { | |
// left: 37, | |
// right: 39, | |
// up: 38, | |
// down: 40, | |
// escape: 27 | |
// }; | |
var _getProp = function( prop, obj ) { | |
if ( obj.hasOwnProperty( prop ) ) { | |
return obj[prop]; | |
} else { | |
return undefined; | |
} | |
}; | |
var keycodes = [ | |
['left', 37], | |
['right', 39], | |
['up', 38], | |
['down', 40], | |
['escape', 2] | |
]; | |
var OnKeyboard = function( options ) { | |
var self = this; | |
self._options = options; | |
self._active = true; | |
self.fire = {}; | |
keycodes.forEach(function( k ) { | |
var n = k[1]; | |
var c = k[0]; | |
var cb = _getProp( c, self._options ) | |
if (typeof cb === 'function') { | |
self.fire[ c ] = function( e, isMetaKey ) { | |
if ( self._active ) { | |
cb( e, isMetaKey ); | |
} | |
}; | |
} else { | |
self.fire[ c ] = false; | |
} | |
}); | |
document.addEventListener( 'keydown', function(e) { | |
keycodes.forEach(function( k ) { | |
var n = k[1]; | |
var c = k[0]; | |
if ( n === e.which && self.fire[c] ) { | |
self.fire[ c ](e, e.metaKey ); | |
} | |
}); | |
}); | |
}; | |
OnKeyboard.prototype.deactivate = function() { | |
this._active = false; | |
}; | |
OnKeyboard.prototype.activate = function() { | |
this._active = true; | |
}; | |
return OnKeyboard; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment