keycontrol.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. define(function(require, exports, module) {
  2. var key = require('./key');
  3. var FOCUS_CLASS = 'hotbox-focus';
  4. var RECEIVER_CLASS = 'hotbox-key-receiver';
  5. function KeyControl(hotbox) {
  6. var _this = this;
  7. var _receiver;
  8. var _actived = true;
  9. var _receiverIsSelfCreated = false;
  10. var $container = hotbox.$container;
  11. _createReceiver();
  12. _bindReceiver();
  13. _bindContainer();
  14. _active();
  15. function _createReceiver() {
  16. _receiver = document.createElement('input');
  17. _receiver.classList.add(RECEIVER_CLASS);
  18. $container.appendChild(_receiver);
  19. _receiverIsSelfCreated = true;
  20. }
  21. function _bindReceiver() {
  22. _receiver.onkeyup = _handle;
  23. _receiver.onkeypress = _handle;
  24. _receiver.onkeydown = _handle;
  25. _receiver.onfocus = _active;
  26. _receiver.onblur = _deactive;
  27. if (_receiverIsSelfCreated) {
  28. _receiver.oninput = function(e) { _receiver.value = null; };
  29. }
  30. }
  31. function _bindContainer() {
  32. $container.onmousedown = function(e) {
  33. _active();
  34. e.preventDefault();
  35. };
  36. }
  37. function _handle(keyEvent) {
  38. if (!_actived) return;
  39. hotbox.dispatch(keyEvent);
  40. }
  41. function _active() {
  42. _receiver.select();
  43. _receiver.focus();
  44. _actived = true;
  45. $container.classList.add(FOCUS_CLASS);
  46. }
  47. function _deactive() {
  48. _receiver.blur();
  49. _actived = false;
  50. $container.classList.remove(FOCUS_CLASS);
  51. }
  52. this.handle = _handle;
  53. this.active = _active;
  54. this.deactive = _deactive;
  55. }
  56. module.exports = KeyControl;
  57. });