常用 js 函数

这里记录一下使用到常用的js文件以及一些常用到的工具类函数。(陆续更新...)

  • rem布局常用方法
 
// 动态计算相应的比例值
function jsNum(num) {
  let lenWindow = document.documentElement.clientWidth;
  let iWidth = lenWindow / 1920;
  let fs = num * iWidth;
  return fs;

// 组件通信
export class EvtMsg {
  evts

  constructor () {
    this.evts = {}
  }

  on (event: string, cb) {
    if(!event || typeof cb !== 'function') return
    if(!this.evts[event]) {
      this.evts[event] = []
    }
    this.evts[event].push(cb)
  }

  emit (event, ...arg) {
    if (!event || !this.evts[event]) return
    const cbs = this.evts[event]
    for(let i=0; i c === cb)
    cbs.splice(idx, 1)
    return
  }

  removeAll () {
    this.evts = {}
  }
}

export const eventBus = new EvtMsg()
}

/** 防抖 */
export const debounce = (fn, delay = 500) => {
  let timerId
  return (...rest) => {
    const args = rest
    if (timerId) clearTimeout(timerId)
    timerId = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

/** 字符串转json */
export function strToJson (str) {
  let result = str
  try {
    result = new Function('return ' + str)()
  } catch(err) {
  } finally {
    return result
  }
}
/** 节流*/
export function throttle (func: Function, wait?: number, options: any = {}) {
  let timer: any = null
  return function (...args) {
    const context = options.context || this
    if (timer) {
      return
    }
    timer = setTimeout(function () {
      func.apply(context, args)
      clearTimeout(timer)
      timer = null
    }, wait || 1000)
  }
}

你可能感兴趣的:(常用 js 函数)