-
Notifications
You must be signed in to change notification settings - Fork 13.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(DomController): organize dom reads/writes
- Loading branch information
1 parent
0af494e
commit cac7164
Showing
3 changed files
with
85 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
/** | ||
* Adopted from FastDom | ||
* https://github.com/wilsonpage/fastdom | ||
* MIT License | ||
*/ | ||
import { nativeRaf } from './dom'; | ||
import { removeArrayItem } from './util'; | ||
|
||
|
||
export class DomController { | ||
private r: Function[] = []; | ||
private w: Function[] = []; | ||
private q: boolean; | ||
|
||
read(fn: Function, ctx?: any): Function { | ||
const task = !ctx ? fn : fn.bind(ctx); | ||
this.r.push(task); | ||
this.queue(); | ||
return task; | ||
} | ||
|
||
write(fn: Function, ctx?: any): Function { | ||
const task = !ctx ? fn : fn.bind(ctx); | ||
this.w.push(task); | ||
this.queue(); | ||
return task; | ||
} | ||
|
||
cancel(task: any) { | ||
return removeArrayItem(this.r, task) || removeArrayItem(this.w, task); | ||
} | ||
|
||
private queue() { | ||
if (!this.q) { | ||
this.q = true; | ||
nativeRaf(timestamp => { | ||
this.flush(timestamp); | ||
}); | ||
} | ||
} | ||
|
||
private flush(timestamp: number) { | ||
let err; | ||
let task; | ||
|
||
try { | ||
// ******** DOM READS **************** | ||
while (task = this.r.shift()) { | ||
task(timestamp); | ||
} | ||
|
||
// ******** DOM WRITES **************** | ||
while (task = this.w.shift()) { | ||
task(timestamp); | ||
} | ||
} catch (e) { | ||
err = e; | ||
} | ||
|
||
this.q = false; | ||
|
||
if (this.r.length || this.w.length) { | ||
this.queue(); | ||
} | ||
|
||
if (err) { | ||
throw err; | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters