Zepto源碼之touch模塊


;(function($){
  var touch = {},
    touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
    longTapDelay = 750,
    gesture,
    down, up, move,
    eventMap,
    initialized = false

  // 滑動方向
  function swipeDirection(x1, x2, y1, y2) {
    // 先判斷水平與垂直方向誰的相對位移比較大,如果水平方向大,那就是水平滑動,否則就是垂直滑動
    return Math.abs(x1 - x2) >=
    // 判斷完了方向再比較兩個手勢點位移,通過位移差判斷是上下左右滑動
      Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
  }

  // 長按
  function longTap() {
    // 清空 longTabTimeout 計時器
    longTapTimeout = null
    // 如果 touch.last 存在,則觸發 longTap 事件,然後清空 touch 對象,方便下次使用
    if (touch.last) {
      touch.el.trigger('longTap')
      touch = {}
    }
  }

  // 取消長按
  function cancelLongTap() {
    // 清空 longTabTimeout 計時器
    if (longTapTimeout) clearTimeout(longTapTimeout)
    longTapTimeout = null
  }

  // 取消全部
  function cancelAll() {
    // 清空所有計時器,然後清空 touch 對象,方便下次使用
    if (touchTimeout) clearTimeout(touchTimeout)
    if (tapTimeout) clearTimeout(tapTimeout)
    if (swipeTimeout) clearTimeout(swipeTimeout)
    if (longTapTimeout) clearTimeout(longTapTimeout)
    touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
    touch = {}
  }

  // 是否爲主觸點
  function isPrimaryTouch(event){
    // 通過檢查事件類型是點擊事件且是主觸點來判斷。只處理手指事件
    return (event.pointerType == 'touch' ||
      event.pointerType == event.MSPOINTER_TYPE_TOUCH)
      && event.isPrimary
  }

  // 是否是點擊事件類型
  function isPointerEventType(e, type){
    // 反正在前端上面噴微軟就是政治正確就是了,爲了微軟專門寫的瀏覽器hack
    return (e.type == 'pointer'+type ||
      e.type.toLowerCase() == 'mspointer'+type)
  }

  // 未註冊的事件,其實也就是檢查一下初始化是否執行過
  function unregisterTouchEvents(){
    if (!initialized) return
    $(document).off(eventMap.down, down)
      .off(eventMap.up, up)
      .off(eventMap.move, move)
      .off(eventMap.cancel, cancelAll)
    $(window).off('scroll', cancelAll)
    cancelAll()
    initialized = false
  }

  // 初始化模塊,其實也就是自執行的一種方式 
  function setup(__eventMap){
    var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType

    unregisterTouchEvents()

    // 根據不同的瀏覽器,給定不同的事件類型,使用在框架內部得以統一
    eventMap = (__eventMap && ('down' in __eventMap)) ? __eventMap :
      ('ontouchstart' in document ?
      { 'down': 'touchstart', 'up': 'touchend',
        'move': 'touchmove', 'cancel': 'touchcancel' } :
      'onpointerdown' in document ?
      { 'down': 'pointerdown', 'up': 'pointerup',
        'move': 'pointermove', 'cancel': 'pointercancel' } :
       'onmspointerdown' in document ?
      { 'down': 'MSPointerDown', 'up': 'MSPointerUp',
        'move': 'MSPointerMove', 'cancel': 'MSPointerCancel' } : false)

    if (!eventMap) return

    // 日常黑微軟,這又是爲了處理 IE
    if ('MSGesture' in window) {
      // 創建一個手勢對象
      gesture = new MSGesture()
      // 綁定對象
      gesture.target = document.body

      $(document)
        .bind('MSGestureEnd', function(e){
        // 綁定事件,分析在IE下的手勢方向,然後觸發對應事件
        // 此段代碼作用類似於 swipeDirection
          var swipeDirectionFromVelocity =
            e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null
          if (swipeDirectionFromVelocity) {
            touch.el.trigger('swipe')
            touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
          }
        })
    }

    down = function(e){
      // 只要不是滑動事件,或者不是向下滑動那麼直接返回,不執行下面步驟
      if((_isPointerType = isPointerEventType(e, 'down')) &&
        !isPrimaryTouch(e)) return
      // 如果是滑動事件,那麼記錄第一根手指的信息
      firstTouch = _isPointerType ? e : e.touches[0]
      // 是單指操作的時候,重置終點信息
      if (e.touches && e.touches.length === 1 && touch.x2) {
        touch.x2 = undefined
        touch.y2 = undefined
      }
      // 記錄觸點信息
      now = Date.now()
      delta = now - (touch.last || now)
      touch.el = $('tagName' in firstTouch.target ?
        firstTouch.target : firstTouch.target.parentNode)
      touchTimeout && clearTimeout(touchTimeout)
      touch.x1 = firstTouch.pageX
      touch.y1 = firstTouch.pageY
      // 檢查是不是雙擊事件
      if (delta > 0 && delta <= 250) touch.isDoubleTap = true
      // 檢查是不是長按事件
      touch.last = now
      longTapTimeout = setTimeout(longTap, longTapDelay)
      // 黑IE,單獨處理IE
      if (gesture && _isPointerType) gesture.addPointer(e.pointerId)
    }

    move = function(e){
    // 只要不是滑動事件,或者不是 move 事件那麼直接返回,不執行下面步驟
      if((_isPointerType = isPointerEventType(e, 'move')) &&
        !isPrimaryTouch(e)) return
      firstTouch = _isPointerType ? e : e.touches[0]
      // 竟然移動了,那肯定不是長按事件,取消長按事件
      cancelLongTap()
      //記錄移動終點的信息
      touch.x2 = firstTouch.pageX
      touch.y2 = firstTouch.pageY
      // 計算手指移動起點終點間的位移
      deltaX += Math.abs(touch.x1 - touch.x2)
      deltaY += Math.abs(touch.y1 - touch.y2)
    }

    up = function(e){
    // 只要不是滑動事件,或者不是 up 事件那麼直接返回,不執行下面步驟
      if((_isPointerType = isPointerEventType(e, 'up')) &&
        !isPrimaryTouch(e)) return
        // 手指竟然鬆開了,那肯定不是長按,取消長按
      cancelLongTap()

      // 如果手指間移動超過30,那麼就是 swipe滑動事件
      if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
          (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))
        // 觸發對應的滑動事件
        swipeTimeout = setTimeout(function() {
          if (touch.el){
            touch.el.trigger('swipe')
            touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
          }
          touch = {}
        }, 0)

      else if ('last' in touch)
        if (deltaX < 30 && deltaY < 30) {
          // 如果 last 存在,那麼不是 swipe 事件。
          tapTimeout = setTimeout(function() {
            var event = $.Event('tap')
            event.cancelTouch = cancelAll
            if (touch.el) touch.el.trigger(event)

            if (touch.isDoubleTap) {
              if (touch.el) touch.el.trigger('doubleTap')
              touch = {}
            }

            else {
              touchTimeout = setTimeout(function(){
                touchTimeout = null
                if (touch.el) touch.el.trigger('singleTap')
                touch = {}
              }, 250)
            }
          }, 0)
        } else {
          touch = {}
        }
        deltaX = deltaY = 0
    }

    $(document).on(eventMap.up, up)
      .on(eventMap.down, down)
      .on(eventMap.move, move)
    $(document).on(eventMap.cancel, cancelAll)
    $(window).on('scroll', cancelAll)

    initialized = true
  }
  // 給對應的事件綁定 callback
  ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
    'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
    $.fn[eventName] = function(callback){ return this.on(eventName, callback) }
  })

  $.touch = { setup: setup }

  $(document).ready(setup)
})(Zepto)

發佈了88 篇原創文章 · 獲贊 41 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章