Back to the index of articles and examples

Tree View with DataTables as nodes

Multiple Tables

One table at a time

Here I am making a couple of trees of a random number of elements and random depth assigning to each node both a label and a key made up of numbers representing each node position in the tree. If you refresh the page, a new random tree will be generated.

I listen to label clicks on each node. If it doesn't have any children, I build a DataTable on it

The data for each node is created dynamically via a function which takes the key to generate the contents of each cell. In normal circumstances, this custom property of the node should serve as the query argument to an XHR request to a server providing the records for that query.

In the first tree, each DataTable is built once and remains there. If a node is collapsed and expanded again, the DataTable in it will be hidden and just shown again not rebuilt. Notice that I turn the label inactive once I create the DataTable under it so that clicking on it will have no effect, ie., it will not recreate the DataTable.

In the second tree, there is only one DataTable for the whole tree. Since the nodes of the tree are set to expand just one at a time (setting nodes multiExpand property to false), I know I don't need more than one table at once.

If the table is not yet created when I get to a leaf node, I do create it, but if there is already a DataTable created, I just move it around manipulating the DOM element where it is contained and asking the DataSource for a new set of data.

I didn't disable the label in this case so that clicking on the label will toggle the visibility of the table.

I enabled caching on the DataSource so that if the data is still there, I won't bother the server again.

The effect on the server can be seen in the logger. I am logging the calls to the function that acts as the data server with a 'warning' category so they are more visible in the logger. Notice that until the cache is filled up (I set it to hold few entries so you could overflow it and see what happens), if the data is cached, the server won't be bothered again

Both tables have cell editing enabled. In the first tree, it is not much of an issue since all tables are visible at all times. In the second tree, since the table is drawn within the label itself, I had to add code to tell when it was the actual tree label that was clicked and when it was the DataTable so that by clicking the label, the node would collapse while by clicking the DataTable the cell editor would pop up but the node would remain expanded.

This example is self-contained, its only dependencies come from the YUI site.