Vue源码中的nextTick的完成逻辑

我们晓得vue中有一个api。Vue.nextTick( [callback, context] )
他的作用是鄙人次 DOM 更新轮回完毕以后实行耽误回调。在修正数据以后马上运用这个要领,猎取更新后的 DOM。那末这个api是怎样完成的呢?你一定也有些疑问或许猎奇。下面就是我的探究,分享给人人,也迎接人人到github上和我举行议论哈~~

起首贴一下vue的源码,然后我们再一步步的剖析

/* @flow */
/* globals MessageChannel */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(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.
    if (isIOS) setTimeout(noop)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

这么多代码,能够猛的一看,能够有点懵,没关系,我们一步一步抽出枝干。起首我们看一下这个js文件里的nextTick的定义

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

我将代码精简一下。以下所示,下面的代码预计就比较轻易看懂了。把cb函数放到会掉行列里去,假如支撑macroTask,则应用macroTask鄙人一个事宜轮回中实行这些异步的使命,假如不支撑macroTask,那就应用microTask鄙人一个事宜轮回中实行这些异步使命。

export function nextTick (cb?: Function, ctx?: Object) {
  callbacks.push(cb)
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
}

这里再次提高一下js的event loop的相干学问,js中的两个使命行列 :macrotasks、microtasks

macrotasks: script(一个js文件),setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks: process.nextTick, Promises, Object.observe, MutationObserver

实行历程:
1.js引擎从macrotask行列中取一个使命实行
2.然后将microtask行列中的一切使命顺次实行完
3.再次从macrotask行列中取一个使命实行
4.然后再次将microtask行列中一切使命顺次实行完
……
轮回往复

那末我们再看我们精简掉的代码都是干什么的呢?我们往异步行列里放回调函数的时刻,我们并非直接放回调函数,而是包装了一个函数,在这个函数里挪用cb,而且用try catch包裹了一下。这是由于cb在运行时失足,我们不try catch这个毛病的话,会致使全部顺序崩溃掉。 我们还精简掉了以下代码

  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }

这段代码是干吗的呢?也就是说我们用nextTick的时刻,还能够有promise的写法。假如没有向nextTick中传入cb,而且浏览器支撑Promise的话,我们的nextTick返回的将是一个Promise。所以,nextTick的写法也能够是以下如许的

 nextTick().then(()=>{console.log("XXXXX")})

vue源码里关于nextTick的封装的思绪,也给我们一些异常有益的启发,就是我们日常平凡在封装函数的时刻,要想同时指出回折衷promise的话,就能够自创vue中的思绪。

大抵的思绪我们已捋顺了。然则为何实行macroTimerFunc或许microTimerFunc就会鄙人一个tick实行我们的回调行列呢?下面我们来剖析一下这两个函数的定义。起首我们剖析macroTimerFunc

let macroTimerFunc

if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

从上边的代码能够看出,假如浏览器支撑setImmediate,我们就用setImmediate,假如浏览器支撑MessageChannel,我们就用MessageChannel的异步特征,假如两者都不支撑,我们就贬价到setTimeout
,用setTimeout来把callbacks中的使命鄙人一个tick中实行

  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }

剖析完macroTimerFunc,下面我们最先剖析microTimerFunc,我把vue源码中关于microTimerFunc的定义轻微精简一下

let microTimerFunc;
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    p.then(flushCallbacks)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

从上边精简以后的代码,我们能够看到microTimerFunc的完成思绪。假如支撑浏览器支撑promise,就用promise完成。假如不支撑,就降低到用macroTimerFunc

over,团体逻辑就是如许。。看着吓人,掰开了以后好好剖析一下,照样挺简朴的。

    原文作者:jessezhao1990
    原文地址: https://segmentfault.com/a/1190000015680531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞