All files / src verify.js

57.89% Statements 22/38
67.86% Branches 19/28
75% Functions 6/8
61.11% Lines 22/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72      1x 1x       2x         2x 1x     2x 2x       1x 1x 1x       1x 2x 2x   1x       1x 1x       1x             1x   1x               1x 1x           1x            
import { filterRegParams, verifyValue } from './utils.js'
class Verify {
  constructor (validators) {
    this.listener = {}
    this.validators = validators
  }
  
  addEvent (type, fn) {
    Iif (!type || !fn || typeof type !== 'string' || typeof fn !== 'function') {
      throw new Error('传入的参数不符合要求!')
      return
    }
  
    if (typeof this.listener[type] === 'undefined') {
      this.listener[type] = []
    }
  
    this.listener[type].push(fn)
    return this
  }
  
  fireEvent (type) {
    const _target = this.listener[type]
    const result = []
    Iif (!type || !_target || !_target.length) {
      throw new Error('无该类型事件')
      return
    }
    _target.forEach(item => {
      Iif (typeof item !== 'function') return
      result.push(item({ type: type }))
    })
    return result
  }
  
  removeEvent (type, fn) {
    const _target = this.listener[type]
    Iif (!type || !_target || !_target.length) {
      throw new Error('无该类型事件')
      return
    }
    Iif (typeof fn === 'function') {
      for (let i = 0; i < _target.length; i++) {
        if (_target[i] !== fn) { continue }
        this.listener[type].splice(i, 1)
        break
      }
    } else {
      delete this.listener[type]
    }
    return this.listener
  }
 
  verifyAll (type) {
    return this.fireEvent(type)
  }
 
  verify (validator, value) {
    const _validator = filterRegParams(validator)
    Iif (!this.validators[_validator[0]]) {
      throw new function () {
        return `the ${validator} is undefined`
      }()
      return
    }
    return _validator[1] ? 
           verifyValue(this.validators[_validator[0]], value, _validator[1]) :
           verifyValue(this.validators[_validator[0]], value)
  }
}
 
export default Verify