2

I'm working on a project with Google's Blockly, but parts of the documentation are incomprehensible. Can someone help me understand the end condition of the following for loop (xml = allXml[i])?

var allXml = Blockly.Xml.workspaceToDom(workspace);
var allCode = [];
for (var i = 0, xml; xml = allXml[i]; i++) {
  var headless = new Blockly.Workspace();
  Blockly.Xml.domToWorkspace(headless, xml);
  allCode.push(Blockly.JavaScript.workspaceToCode(headless));
  headless.dispose();
}

I imagine the loop will exit when allXml[i] is undefined, but how can you iterate through an XML object like this? It seems to always be returning undefined and skipping the loop entirely.

Thanks for you help

Definitions for most of the function can be found at https://code.google.com/p/blockly/source/browse/trunk/core/xml.js?r=1614

And the doc page I pulled this from is https://developers.google.com/blockly/custom-blocks/code-structure?hl=en

user3708584
  • 161
  • 1
  • 1
  • 4
  • You're correct about how the loop terminates. As for iterating through XML like that, they must have defined it as some kind of array. Try `console.log(allXml)` to see what kind of object it is. – Mike Cluck Jan 15 '16 at 22:01
  • 1
    I have. It is actual xml. It looks like xml and behaves the way you would expect xml to behave with .childnodes and .childElementCount. – user3708584 Jan 15 '16 at 22:06

2 Answers2

1

I could not find this code in the repo on github, so I guess it is a bit older example in the docs.

But if you will have a look at the Blockly.Xml.workspaceToDom() function's implementation, you will see a very similar thing there.

  var blocks = workspace.getTopBlocks(true);
  for (var i = 0, block; block = blocks[i]; i++) {
    var element = Blockly.Xml.blockToDom_(block);
    //...
    xml.appendChild(element);
  }

The idea here is to iterate over all branches of code. The top block has no top connection (it starts a new branch). The getTopBlocks() returns an array {!Array.<!Blockly.Block>}.

Considering that the documentation is showing it in a section about parallel execution, I think it will be related to the fact, that you can have more unconnected branches of code... and the exact implementation just changed over time.

Tom
  • 564
  • 1
  • 3
  • 8
0

As per the code, return type of Blockly.Xml.workspaceToDom(workspace) is {!Element}.

It basically returns a DOM node created using goog.dom.createDom('xml');. And for each top level block it is appending a DOM node to it.

So basically the code snippet in question is looping through all the DOM nodes corresponding to the top level blocks.

Nithin Kumar Biliya
  • 2,763
  • 3
  • 34
  • 54