Created
March 20, 2013 23:50
-
-
Save shawnbot/5209568 to your computer and use it in GitHub Desktop.
queue + d3 = asynchronous, parallelized, event-dispatching load queue
This file contains hidden or 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
| var loadQueue = function() { | |
| var q = queue(), | |
| defer = q.defer, | |
| dispatch = d3.dispatch("progress", "complete"), | |
| requests = []; | |
| q.defer = function(load, url) { | |
| return defer(function(callback) { | |
| var req = load(url, function(error, data) { | |
| req.loaded = req.total; | |
| req.progress = 1; | |
| update(); | |
| callback.apply(null, arguments); | |
| }) | |
| .on("progress", function() { | |
| var e = d3.event; | |
| req.loaded = e.loaded; | |
| req.total = e.total; | |
| req.progress = e.loaded / e.total; | |
| }); | |
| req.total = req.loaded = req.progress = 0; | |
| requests.push(req); | |
| }); | |
| }; | |
| function update() { | |
| var total = 0, | |
| loaded = 0, | |
| progress = 0; | |
| requests.forEach(function(req) { | |
| total += req.total; | |
| loaded += req.loaded; | |
| progress += req.progress; | |
| }); | |
| progress /= requests.length; | |
| dispatch.progress({ | |
| total: total, | |
| loaded: loaded, | |
| progress: progress | |
| }); | |
| if (progress >= 1) { | |
| dispatch.complete({ | |
| loaded: loaded | |
| }); | |
| } | |
| } | |
| d3.rebind(q, dispatch, "on"); | |
| return q; | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good catch, Mike. Thanks!