Hiding nodes in a flex tree component keeping the

2020-05-04 10:04发布

问题:

I have a tree with a dataprovider which takes the following form:

<details name="Cars">
    <contact_person>aaaa</contact_person>
    <list>
        <car type="A">
            <car name="A1"/>
            <car name="A2"/>
        </car>
        <car type="B">
            <car name="B1"/>
            <car name="B2"/>
        </car>
    </list>
</details>

I want the tree to be shown like this

Cars
     A
          A1
          A2
     B
          B1
          B2

That is I want to hide the contact_person and list nodes.Deleting the nodes from the dataprovider cannot be done.So what i did was to create a custom tree data descriptor by extending DefaultDataDescriptor.Then override the getChildren method and applied a filterfunction to the collection returned by super.getChildren.The problem is when i hide the 'list' node I cannot have the child nodes to show up.So is there any way I can hide 'list' but show the children of 'node'?

回答1:

Passing XML as a dataProvider is good for demos and does not work when it comes to the real product. The common practice is parsing the XML into strong-typed objects:

public class Details 
{ 
    public function Details(xml:XML)
    {
        label = xml.@name;
        var childrenArray:Array = [];
        for each (var carNode:XML in xml.list.car)
        {
            childrenArray.push(new CarType(carNode));
        }
        children = new ArrayCollection(childrenArray);
    }

    [Bindable]
    public var label:String;

    [Bindable]
    public var children:ArrayCollection /* of CarType */;
}

public class CarType
{
    public function CarType(xml:XML)
    {
        label = xml.@type;
        var childrenArray:Array = [];
        for each (var carNode:XML in xml.car)
        {
            childrenArray.push(new Car(xml));
        }
        children = new ArrayCollection(childrenArray);
    }

    [Bindable]
    public var label:String;

    [Bindable]
    public var children:ArrayCollection /* of Car */;
}

public class Car
{
    public function Car(xml:XML)
    {
        label = xml.@name;
    }

    [Bindable]
    public var label:String;
}

Usage:

var xml:XML = <details name="Cars">...</details>;
var details:Details = new Details(xml);
var tree:Tree = new Tree();
tree.dataProvider = new ArrayCollection([ details ]);

To simplify the code I parse XML in constructors. Variables can be also turned into read-only properties.