键入事件处理程序跳过第一个事件

时间:2019-07-02 12:58:42

标签: javascript event-handling barcode barcode-scanner

借助此solution 我写了一个简单的条形码处理程序绑定:操作员可以通过扫描表单上的条形码来启动某些功能。

我不知道为什么,但是加载文档后的第一个事件(符号)被keyup-handler(条形码扫描器._keyup())忽略。它使我需要在初始化后立即生成虚拟keyup-event。同时,重点突出的GUI元素正确填充-用前导符号(

var BarcodeScanner = function () {
  this.initialize.apply(this, arguments);
}

BarcodeScanner.prototype = {
  initialize: function () {
    let self = this;

    // Change context for document's event handler
    $(document).on("keyup", $.proxy(self._keyup, self));

    // I dont know why this thing skips first event - and symbol
    // This is my temporary solution
    //let e = $.Event('keyup');
    //e.which = 17; // Control
    //$(document).trigger(e);
  },
  _timeoutHandler: 0,
  _inputString: '',
  _inputKeyCodes: [],
  references: {},
  barcodescanned: function (input_string) {
  },
  _keyup: function (event) {
    let self = this;

    if (self._timeoutHandler) {
      clearTimeout(self._timeoutHandler);
      // this._inputString += String.fromCharCode(event.keyCode);
      self._inputKeyCodes.push(event.keyCode);
    }

    self._timeoutHandler = setTimeout($.proxy(function () {
      if (self._inputKeyCodes.length <= 10) {
        self._inputKeyCodes = [];
        return;
      }

      console.log(self._inputKeyCodes);
      self.convertInputString();
      self._inputKeyCodes = [];

      $.each(this.references, function (barcode, handler) {
        if (barcode.startsWith(self._inputString)) {
          handler(barcode);
        }
      });

    }, this), 20);
  },
  convertInputString: function () {
    let self = this;

    self._inputString = '';

    let shift = false;
    $.each(self._inputKeyCodes, function (idx, keyCode) {
      if (keyCode === 16) { // Shift
        shift = true;
        return true; // next

      } else if (keyCode < 32) { // Ignore
        return true; // next

      } else if (keyCode >= 65 && keyCode <= 90) { // Letter
        if (!shift) {
          keyCode += 32; // Lowercase
        }
        shift = false;
      }

      let symbol = String.fromCharCode(keyCode);
      self._inputString += symbol;
    });
  }
}

用法:

      let doThis = function (barcode) {
        console.log('Doing this');
      }
      let doThat = function (barcode) {
        console.log('Doing that');
      }

      let barcode_scanner = require('barcode_scanner.js');
      barcode_scanner.references = {
        'w6oqacBEfT': doThis,
        'fSPOhbHdgy': doThat,
      };

输出:

(14) [16, 83, 16, 80, 16, 79, 72, 66, 16, 72, 68, 71, 89, 13]
(15) [70, 16, 83, 16, 80, 16, 79, 72, 66, 16, 72, 68, 71, 89, 13]
Doing that

0 个答案:

没有答案