Detect when input box filled by keyboard and when by barcode scanner.

前端 未结 11 2083
星月不相逢
星月不相逢 2020-12-01 00:44

How I can programmatically detect when text input filled by typing on keyboard and when it filled automatically by bar-code scanner?

11条回答
  •  臣服心动
    2020-12-01 01:26

    For ES6 2019 version of Vitall answer.

    const events = mitt()
    
    class BarcodeScaner {
      initialize = () => {
        document.addEventListener('keypress', this.keyup)
        if (this.timeoutHandler) {
          clearTimeout(this.timeoutHandler)
        }
        this.timeoutHandler = setTimeout(() => {
          this.inputString = ''
        }, 10)
      }
    
      close = () => {
        document.removeEventListener('keypress', this.keyup)
      }
    
      timeoutHandler = 0
    
      inputString = ''
    
      keyup = (e) => {
        if (this.timeoutHandler) {
          clearTimeout(this.timeoutHandler)
          this.inputString += String.fromCharCode(e.keyCode)
        }
    
        this.timeoutHandler = setTimeout(() => {
          if (this.inputString.length <= 3) {
            this.inputString = ''
            return
          }
          events.emit('onbarcodescaned', this.inputString)
    
          this.inputString = ''
        }, 10)
      }
    }

    Can be used with react hooks like so:

    const ScanComponent = (props) => {
      const [scanned, setScanned] = useState('')
      useEffect(() => {
        const barcode = new BarcodeScaner()
        barcode.initialize()
        return () => {
          barcode.close()
        }
      }, [])
    
      useEffect(() => {
        const scanHandler = code => {
          console.log(code)
          setScanned(code)
        }
    
        events.on('onbarcodescaned', scanHandler)
        return () => {
          events.off('onbarcodescaned', scanHandler)
        }
      }, [/* here put dependencies for your scanHandler ;) */])
      return 
    {scanned}
    }

    I use mitt from npm for events, but you can use whatever you prefer ;)

    Tested on Zebra DS4208

提交回复
热议问题