0

I have a single page d3.js based browser application with a (likely) varying number of dynamically loaded elements. Ideally I'd like these configured in their entirety from json files, but converting the currently hard-coded nested callbacks (intended to force asynch behaviour, see the lower code block below) is proving something of a stumbling block.

function load_page_element(element, force_asynch) {

  d3.json(("path_to/" + element + ".json"), function(data) {    
    // Attach the element to the DOM
    // Set up some event handling
    // Enjoy the fireworks
  });

  force_asynch();
};

// Hard-coded nested asynch-forcing callbacks
load_page_element("colours", function() {
  load_page_element("sounds", function() {
    load_page_element ("tools", function() {
      load_page_element ("tutorials", function() {
        load_page_element ("videos", function() {
          load_page_element ("games", function() {
            console.log("Asynch element loading completed, in order.");
          });
        });
      });
    });
  });
});

I anticipate some kind of recursive call structure into which I can plug the element names ("colours", "sounds" etc), but have yet to hit on a mechanism that actually works. Presumably this has all been done before, but darned if I can find any examples.. Any suggestions are welcome..

user1019696
  • 453
  • 1
  • 5
  • 15
  • maybe use the new javascript promises when and then syntax: http://stackoverflow.com/questions/6080050/how-does-jquerys-promise-method-really-work – nathan hayfield Feb 11 '14 at 22:15

1 Answers1

1

Use queue.js for this. See also this example. The code looks like this:

queue()
  .defer(request, "1.json")
  .defer(request, "2.json")
  .defer(request, "3.json")
  .awaitAll(ready);

function ready(error, results1, results2, results3) {
  // do something
}
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Mike Bostock's second example (under your first link) is the perfect fit. I can feed it with a list of files obtained using a separate d3.json() call. Thanks! – user1019696 Feb 12 '14 at 12:30