TreeView from DataSource

Trees are often represented in tables in a server-side database. The way to represent a hierarchical structure such as that of a tree in a shallow table is to make child records to hold a reference to their parents.

This function uses a DataSource to fetch a table from the server and assemble the hierarchical structure out of those child ==> parent relationthips.

The function is included along this page as YAHOO.SATYAM.buildTreeFromDataSource and can be freely copied to a suitable JavaScript library file; may this serve as a license agreement: feel free.

The code above calls that function passing as arguments a reference to an HTMLElement, a div, that will hold the tree, a reference to an instance of a DataSource which retrieves the data from the server, a function and several configuration options.

The function will receive a reference to the tree just created based on the definition retrieved. Fetching data from a remote source is an asynchronous event so the tree cannot be created immediatly, it will be created as soon as the data is received and when that happens, this function will be called.

The configuration options has two mandatory attributes, nodeId is a string which corresponds to the name of the field that serves as the primary key of the records in the database table. parentRef is the name of the field that contains the references to the parent of each record. These two attributes are mandatory.

The scope configuration option allows to adjust the scope of the callback function. The translate option is made of an object literal where each item defines field names that are to be translated. Each entry should be in the form "oldName":"newName" or "oldName":null, where the second indicates that the field should be deleted. In the above example, both the primary key and the reference to the primary key are deleted, since they are no longer needed, while the "text" field read from the server is translated into "label" so it can be used to create TextNodes