vue之nextTick源碼閱讀

功能:在下次 DOM 更新循環結束以後執行延遲迴調。在修改數據以後當即使用這個方法,獲取更新後的 DOM。
默認使用micro, 可是公開了當須要的時候,能夠配置強制使用宏任務的方法:在綁定DOM事件的時候,是強制macro

用到的知識點:

  1. setImmediate: https://developer.mozilla.org... 事件延遲執行,惋惜只有ie支持
  2. messageChannel :https://zhuanlan.zhihu.com/p/... 又一個實現異步的方法。web通訊
  3. istanbul:代碼執行覆蓋率

實現

將nextTick的回調函數推入任務棧中。web

nextTick裏面的回調函數:
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  // 清空callbacks 清空棧
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    // 執行每個方法
    copies[i]()
  }
}
export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  // 有可能有多個nextTick被推入到棧裏面,因此將這些所有存放在callbacks裏面,以後按照順序執行
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  // pending記錄是否開始執行
  if (!pending) {
    pending = true
    setTimeout(() => flushCallbacks())
  }
  // 若是沒有傳入參數,直接返回一個Promise
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

在2.4版本以前,nextTick 就是單純的一個micro tasks,可是micro tasks的優先級過高了,因此擴展了能夠將nextTick配置爲macro的方法promise

macro tasks實現:瀏覽器

if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    // 強制宏觀實現,在瀏覽器執行完全部之後再去執行回調
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  // 使用messageChannel實現
  const channel = new MessageChannel()
  const port = channel.port2
  // 監聽flushCallbacks,當port1接受到信息的時候(也就是瀏覽器執行完全部代碼後),再去執行flushCallbacks
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    // port2發送消息1
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  // 若是不支持setImmediate和MessageChannel,就用setTimeout,這個會佔用不少內存,因此不是最優解法
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

micro tasks實現:bash

if (typeof Promise !== 'undefined' && isNative(Promise)) {
  // 微觀是用Promise是實現的
  const p = Promise.resolve()
  microTimerFunc = () => {
    p.then(flushCallbacks)
    // in problematic UIWebViews, Promise.then doesn't completely break, but
    // it can get stuck in a weird state where callbacks are pushed into the
    // microtask queue but the queue isn't being flushed, until the browser
    // needs to do some other work, e.g. handle a timer. Therefore we can
    // "force" the microtask queue to be flushed by adding an empty timer.
    // 在有問題的UIWebViews裏面,then可能不會徹底的返回,不會執行 ===> 處理方式:「強制」經過添加空計時器刷新微任務隊列。( 不明白??)
    if (isIOS) setTimeout(noop)
  }
} else {
  // fallback to macro
  // 若是沒有promise就仍是使用宏觀
  microTimerFunc = macroTimerFunc
}

以上兩個都實現了優雅降級異步

相關文章
相關標籤/搜索