diff options
-rw-r--r-- | examples/index.html | 60 | ||||
-rw-r--r-- | lib/dombatcher.js | 37 |
2 files changed, 97 insertions, 0 deletions
diff --git a/examples/index.html b/examples/index.html new file mode 100644 index 0000000..4fd62fb --- /dev/null +++ b/examples/index.html @@ -0,0 +1,60 @@ +<!DOCTYPE html> +<html> +<head> +<meta charset="UTF-8"> +<title>title</title> +<style> + + + +</style> +</head> +<body> + <div class='div1'></div> + <div class='div2'></div> + <div class='div3'></div> + <script type="text/javascript" src="../lib/dombatcher.js"></script> + <script> + + + var batch = new DomBatcher(); + + batch.write(function() { + console.log('write1'); + }); + + batch.read(function() { + console.log('read1'); + }); + + batch.read(function() { + console.log('read1'); + }); + + batch.write(function() { + console.log('write1'); + }); + + + setTimeout(function() { + var batch = new DomBatcher(); + + batch.write(function() { + console.log('write2'); + }); + + batch.read(function() { + console.log('read2'); + }); + + batch.read(function() { + console.log('read2'); + }); + + batch.write(function() { + console.log('write2'); + }); + }, 400); + </script> +</body> +</html>
\ No newline at end of file diff --git a/lib/dombatcher.js b/lib/dombatcher.js new file mode 100644 index 0000000..fe5590e --- /dev/null +++ b/lib/dombatcher.js @@ -0,0 +1,37 @@ + +/** + * Util + */ + +function dispatch(fns) { + var fn; + while (fn = fns.shift()) fn(); +} + +/** + * Lib + */ + +function DomBatcher() { + this.reads = []; + this.writes = []; +} + +DomBatcher.prototype.read = function(fn) { + this._dispatcher = this._dispatcher || this.dispatch(); + this.reads.push(fn); +}; + +DomBatcher.prototype.write = function(fn) { + this._dispatcher = this._dispatcher || this.dispatch(); + this.writes.push(fn); +}; + +DomBatcher.prototype.dispatch = function() { + var self = this; + return setTimeout(function() { + dispatch(self.reads); + dispatch(self.writes); + delete self._dispatcher; + }, 0); +}; |