Login Register

Scripting Trees

In Actions we saw how to hook a piece of code into onClick. That's not all. With JavaScript and a Tree, you can style and manipulate trees in all sorts of combinations.

Adding an Icon or Class to a Node

OnClick is an extension point, which we'll cover in detail in Part 3. Three other extension points are used in drawing the tree nodes:

  • String getIconClass(/* dojo.data.Item */ item) takes in an item and returns a String specifiying a CSS class for the icon. The class should have a CSS style specifying a background url, pointing at the image. We saw this in Example 2 for styling mail icons.
  • String getLabelClass(/*dojo.data.Item*/ item) returns a CSS class applied to a label.
  • String getLabel(/*dojo.data.Item*/ item) returns an actual label. This is useful when the data source label is not sufficient for display - e.g. displaying "First Name Last Name" when the data source label is the SSN.

Here is an example of coloring our Pop Tarts labels. Notice the loose coupling here. If another category of Pop Tarts are introduced in the data source, you only need to add a corresponding class to poptarts.css:

.Cinammon {
    color:red;
}
.Chocolate {
   color:brown;
}
.Fruit {
   color: blue;
}

And the getLabelClass is straightforward:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
        @import "http://o.aolcdn.com/dojo/1.0.0/dijit/themes/tundra/tundra.css";
        @import "http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.css";
        @import "poptarts.css";
    </style>
    <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js"
            djConfig="parseOnLoad: true">
</script>
    <script>
        dojo.require("dojo.data.ItemFileReadStore");
        dojo.require("dijit.Tree");
        dojo.require("dojo.parser");
   </script>
</head>
<body class="tundra">
        <div dojoType="dojo.data.ItemFileReadStore"
             url="poptarts_direct.txt" jsid="popStore" />

        <div dojoType="dijit.Tree" store="popStore" labelAttr="name"
             label="Pop Tarts">

                <script type="dojo/method" event="getLabelClass" args="item">
                if (item != null && popStore.getValue(item, "type") == 'category') {
                    // For name=Chocolate, return class Chocolate etc.
                        return popStore.getValue(item, "name");
                }
            </script>
        </div>
</body>
</html>

Adding, Removing and Disabling Nodes

AttachmentSize
poptarts_direct.txt380 bytes