2

I have some trouble with a recursive function for creating a TreeView (using MetroUI) from some XML-Data. In the first scope, so the first level of the Tree, is created as expected, but the second one is not created. My XML-data has the following structure:

<tree>
  <sitenode>
    <name>First Element</name>
    <children>
      <sitenode>
        ...
      </sitenode>
    </children>
  </sitenode>
</tree>

The JavaScript-Code I am using is this one:

var tree = $('#dlgEditorCreateNewSiteSelParent').data('treeview');

/* Helper-function for Recursion */
function dlgEditorCreateNewSiteCreateParentTreeViewNodes(nodes, parent) {
  var i, j;
  /* Alle knoten durchlaudfen */
  for (i = 0; i < nodes.length; i++) {

    /* Add leaf */
    var node = tree.addLeaf(parent, $(nodes[i]).find('>name').text());

    /* Children */
    var children = $(nodes[i]).find('children > sitenode');

    for (j = 0; j < children.length; j++) {
      /* REKURSION */
      //alert('childre child nr. '+j+' with name '+$(children[j]).find('> name').text());
      dlgEditorCreateNewSiteCreateParentTreeViewNodes(children[j], node);
    }
  }
}

var roots = $(result).find('tree > sitenode');
dlgEditorCreateNewSiteCreateParentTreeViewNodes(roots, false);
By debugging the code with Firefox, it seems to be like if the first processing-scope functions properly, but in the second one (so by processing the children), the Debugger immediately jumps (after calling the function recursively) into the second for-loop and most of my variables are "undefined".

I have already searched for some comparable problems, but everything I found was about the counter-variables scope.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Niklas F
  • 21
  • 1

1 Answers1

0
  for (j = 0; j < children.length; j++) {
  /* REKURSION */
  //alert('childre child nr. '+j+' with name '+$(children[j]).find('> name').text());
  dlgEditorCreateNewSiteCreateParentTreeViewNodes(children[j], node);
}

This should work, I am not sure though..

children.forEach(function(child) {
    dlgEditorCreateNewSiteCreateParentTreeViewNodes(child, this);
}, node);
cedzz
  • 389
  • 2
  • 9
  • thanks, but this did not work. But I have found another way to solve the issue by passing th complete array into the recursion. The last days I was a little bit at the loss (do you say it like this in englisch?) – Niklas F Mar 03 '16 at 10:37