The ClientTreeIterator helper scans a hierarchical data structure and decides which template to use for each data element it meets during this processing. The developer is required to provide just a list of templates, and a function that selects a template given a data item. After that, the provided templates are used as building blocks to produce the whole UI of the page (or of a part of the page) as soon as a new client ViewModel(or a new part of it, such as a Workspace) is sent to the client side. Each Template, in turn, may istantiate other templates by calling the _with, and _foreach knockout.js extensions.
Since the Data Moving Plug-in is able to compile any Razor template into a client side template, we can put everything in the templates provided to the ClientTreeIterator, _with, and _foreach : paged grids and/or complex controls such as Dual selects , or whole Data Moving Forms.
We will see how the TreeIterator works with a simple example: automatically building a multipage JQuery mobile menu based on nested lists, from the information contained in a hierarchy of objects. We will use the Mvc Controls Toolkit SimpleMenuItem class to define each menu item.
As first step we declare all needed templates:
This task is easily accomplished with the fluent interface of the DeclareClientTemplates helper. The unique argument of this helper is the templates base name. All templates are named by adding an integer suffix to this base name: the firts template is named “mobile_menu0”, the second one “mobile_menu1”, and so on.
Our first template defines the startup template, that is, the initial template that starts the rendering. The startup template is not necessarily the first one, but the startup template is declared in the call to the TreeIterator helper. Then we have the template to use for displaying pure text, the template of a menu item that links to a target page, the template of a menu item that links to a target page to be opened in a new browser window, and finally the template to be used for a menu item that has sub-menu items.
As you can see both the startup template and the last template call RecurIteration on the children of the current SimpleMenuItem. This is the way the TreeIterator visits recursively, the whole data structure. In general, each, template may contains several calls to RecurIteration if the object has several children arrays. Inside each templates contents may be turned on/off with the help of the _if Mvc Controls Toolkit knockout.js extension.
Once we have defined all templates we need just to render them:
The above code is self-explanatory. Finally, we may call the TreeIterator helper that "will do the job”:
The nice part, is that as soon as we substitute the root of the objects hierarchy with a different data item the UI of the menu is changed immediately to reflect the new data.