wip: lifecycle hooks

This commit is contained in:
Evan You
2019-05-28 19:36:15 +08:00
parent 9dd133b1e9
commit 19ed750078
7 changed files with 225 additions and 72 deletions

View File

@@ -1,5 +1,6 @@
const queue: Array<() => void> = []
const postFlushCbs: Array<() => void> = []
const queue: Function[] = []
const postFlushCbs: Function[] = []
const reversePostFlushCbs: Function[] = []
const p = Promise.resolve()
let isFlushing = false
@@ -18,20 +19,39 @@ export function queueJob(job: () => void, onError?: (err: Error) => void) {
}
}
export function queuePostFlushCb(cb: () => void) {
if (postFlushCbs.indexOf(cb) === -1) {
postFlushCbs.push(cb)
export function queuePostFlushCb(cb: Function | Function[]) {
queuePostCb(cb, postFlushCbs)
}
export function queueReversePostFlushCb(cb: Function | Function[]) {
queuePostCb(cb, reversePostFlushCbs)
}
function queuePostCb(cb: Function | Function[], queue: Function[]) {
if (Array.isArray(cb)) {
queue.push.apply(postFlushCbs, cb)
} else {
queue.push(cb)
}
}
const dedupe = (cbs: Function[]): Function[] => Array.from(new Set(cbs))
export function flushPostFlushCbs() {
const cbs = postFlushCbs.slice()
let i = cbs.length
postFlushCbs.length = 0
// post flush cbs are flushed in reverse since they are queued top-down
// but should fire bottom-up
while (i--) {
cbs[i]()
if (reversePostFlushCbs.length) {
const cbs = dedupe(reversePostFlushCbs)
reversePostFlushCbs.length = 0
let i = cbs.length
while (i--) {
cbs[i]()
}
}
if (postFlushCbs.length) {
const cbs = dedupe(postFlushCbs)
postFlushCbs.length = 0
for (let i = 0; i < cbs.length; i++) {
cbs[i]()
}
}
}