Skip to content

Commit

Permalink
nextTick实现并替代watcher setTimeout方法
Browse files Browse the repository at this point in the history
  • Loading branch information
helloforrestworld committed Feb 18, 2020
1 parent cf8c09b commit 66dc041
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
36 changes: 36 additions & 0 deletions source/vue/observe/nextTick.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// 维护一个事件队列,等同步事件执行完毕后清空callbacks队列
// Promise(微任务) MutationObserver(微任务) setImmediate(宏任务) setTimeout(宏任务)
// 在异步队列中,微任务优先级更高,所以做了一个优化。
// Vue.$nextTick(cb)

const callbacks = []

function flushCallbacks() {
callbacks.forEach(cb => cb())
}

export default function nextTick(cb) {
callbacks.push(cb)

const timerFunc = () => {
flushCallbacks()
}

if (Promise) {
return Promise.resolve().then(flushCallbacks)
}

if (MutationObserver) {
const observer = new MutationObserver(timerFunc)
const textNode = document.createTextNode('1')
observer.observe(textNode, { characterData: true })
textNode.textContent = '2'
return
}

if (setImmediate) {
return setImmediate(timerFunc)
}

setTimeout(timerFunc, 0)
}
8 changes: 4 additions & 4 deletions source/vue/observe/watcher.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { pushTarget, popTarget } from './dep'
import nextTick from './nextTick'

let id = 0 // 每个watcher的标识
class Watcher {
Expand Down Expand Up @@ -35,7 +36,7 @@ class Watcher {
}

update() {
console.log('update1')
console.log('update')
queueWatcher(this)
}

Expand All @@ -56,7 +57,7 @@ class Watcher {

const queueIds = new Set()
let queue = []
function flaskQueue() {
function flushQueue() {
if (!queue.length) return
queue.forEach(watcher => watcher.run())
queueIds.clear()
Expand All @@ -69,8 +70,7 @@ function queueWatcher(watcher) {
queueIds.add(id)
queue.push(watcher)

// TODO replace with nextTick
setTimeout(flaskQueue, 0)
nextTick(flushQueue)
}
}

Expand Down

0 comments on commit 66dc041

Please sign in to comment.