我正在处理树组件,我在为这棵树填充数据提供程序时遇到了一些问题。
我从数据库中获取的数据是一个简单的值对象数组。每个值对象都有2个属性。 ObjectID和ParentID。对于父项,ParentID为null,对于子项,ParentID是父项的ObjectID。
非常感谢任何帮助。
基本上树应该是这样的:
Parent1
Child1
Child1
Child2
Child1
Child2
Parent2
Child1
Child2
Child3
Child1
这是我正在测试的当前代码:
public function setDataProvider(data:Array):void
{
var tree:Array = new Array();
for(var i:Number = 0; i < data.length; i++)
{
// do the top level array
if(!data[i].parentID)
{
tree.push(data[i], getChildren(data[i].objectID, data));
}
}
function getChildren(objectID:Number, data:Array):Array
{
var childArr:Array = new Array();
for(var k:Number = 0; k < data.length; k++)
{
if(data[k].parentID == objectID)
{
childArr.push(data[k]);
//getChildren(data[k].objectID, data);
}
}
return childArr;
}
trace(ObjectUtil.toString(tree));
}
以下是我的数据的横截面:
ObjectID ParentID
1 NULL
10 NULL
8 NULL
6 NULL
4 6
3 6
9 6
2 6
11 7
7 8
5 8
答案 0 :(得分:1)
那么,你遇到的实际问题是什么?
在我看来,您实际上并没有在dataProvider中创建任何子项。每个对象都应该有孩子。这是您的代码,略有修改,但完全可运行的代码版本:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
[Bindable]
public var data : Array = ([
{objectID:1, parentID:null},
{objectID:10, parentID:null},
{objectID:8, parentID:null},
{objectID:6, parentID:null},
{objectID:5, parentID:6},
{objectID:4, parentID:6},
{objectID:9, parentID:6},
{objectID:2, parentID:6},
{objectID:11, parentID:7},
{objectID:7, parentID:8},
{objectID:5, parentID:8},
]);
[Bindable]
public var dataProvider : Array;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
setDataProvider(data);
}
public function setDataProvider(data:Array):void
{
var tree:Array = new Array();
for(var i:Number = 0; i < data.length; i++)
{
// do the top level array
if(!data[i].parentID)
{
data[i].children = getChildren(data[i].objectID, data);
tree.push(data[i]);
}
}
function getChildren(objectID:Number, data:Array):Array
{
var childArr:Array = new Array();
for(var k:Number = 0; k < data.length; k++)
{
if(data[k].parentID == objectID)
{
childArr.push(data[k]);
//getChildren(data[k].objectID, data);
}
}
return childArr;
}
// trace(ObjectUtil.toString(tree));
dataProvider = tree;
}
]]>
</fx:Script>
<mx:Tree id="treeObject" dataProvider="{dataProvider}" />
</s:Application>