2

In the d3js tree sample, I tried to move the call to update outside the d3.json function. When I did that, I get :

TypeError: d is undefined

Here is the code (the function here is slightly different from the link to the example). Notice that I moved the call to update outside the d3.json function. Note that root is a global variable.

  d3.json("../data/flare.json", function(json) {   
     root = json;   
     root.x0 = height / 2;   
     root.y0 = 0;

    function collapse(d) {
      if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
      }   
    }

   root.children.forEach(collapse);   
   // move this out   
   // update(root); 
});

update(root);

function update(source) {.....
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
nilanjan
  • 661
  • 3
  • 9
  • 18

2 Answers2

3

d3.json is an asynchronous call. This means that the call will return immediately, but the code in the handler won't run until later. In your case, this means that root is not defined (or empty) when you're calling update(root).

In short, you have to call update(root) from inside the callback of d3.json. While there are a few possibilities to make it work outside of the callback, those are much more involved and complex.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Lars Kotthoff can you share the other ways to make the function call work outside the callaback. I can see it works when I call it from an html element, i.e., in response to an event. I am not sure if I can generate an event from javascript – nilanjan Jan 17 '14 at 14:20
  • 1
    [This question](http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) explains how to do it. – Lars Kotthoff Jan 17 '14 at 14:37
0

We can't use the root variable to outside function ,because root is the local variable for that function.If you want to use outside ,you will make root as the global varible for save that json;

var root;
    d3.json("../data/flare.json", function(json) {   
     root = json;   
     root.x0 = height / 2;   
     root.y0 = 0;

    function collapse(d) {
      if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
      }   
    }

   root.children.forEach(collapse);   
   // move this out   
   // update(root); 
});



function update(source) {.....
Manoj
  • 1,860
  • 1
  • 13
  • 25