转载

最近在做树相关的一些东东,网上找了很多资料,都是xml作为tree数据源的,关于ArrayCollection作为为数据源的很少。在这做一个小小的总结,以便大家查找。

首先大家知道Tree使用的数据是分等级的,就是说,数据有多个等级:分支节点和叶子节点。与之相反的是,DataGrid 和 List 控件使用的数据都不是分等级的。 所以tree的添加删除比起DataGrid 和 List 更麻烦一点;tree是通过在ArrayCollection里面嵌套ArrayCollection将ArrayCollection变成分等级的:

程序代码

[Bindable]

private var companyData:ArrayCollection = new ArrayCollection(

[ {type:"department", title:"Finance", children:new ArrayCollection(

                                                         [ {type:"employee", name:"John H"},

                                                           {type:"employee", name:"Sam K"} ] ) },

   {type:"department", title:"Engineering", children: new ArrayCollection(

                                                       [ {type:"employee", name:"Erin M"},

                                                         {type:"employee", name:"Ann B"} ] ) },

   {type:"department", title:"Operations", children: new ArrayCollection()}

] );

 

在这个结构里你会发现一个节点只要有子节点,子节点域的名字就是children –Tree会通过这个来区分分支节点和叶子节点。对于这个数据你也需要一个labelFunction,这样Tree才知道在每个节点上显示什么:

 

程序代码

 

private function treeLabel( item:Object ) : String

{

     if( item.type == "department" ) 

         return item.title;

     else 

         return item.name;

}

 

如何添加节点:

        向ArrayCollection添加一个节点的时候你只需要在结构中需要该节点的地方添加它就可以了。下面的代码展示了如何添加一个新的department(顶层的)节点:

 

程序代码

 

var newNode:Object = {type:"department",title:"Administration"};

var newEmployee:Object = {type:"employee",name:"Mark C"};

newNode.children = new ArrayCollection( [newEmployee] );

companyData.addItem(newNode);

 

下面展示的是如何向已经存在的Operations department添加一个新的employee节点:

 

程序代码

 

var newNode:Object = {type:"employee", name:"Beth T"};

for(var i:Number=0; i < companyData.length; i++) {

     var item:Object = companyData.getItemAt(i);

     if( item.title == "Operations" ) {

         var children:ArrayCollection = item.children;

         children.addItem(newNode);

         companyData.itemUpdated(item);

         empName.text = ""; 

         break;

     }

}

删除节点

       在ArrayCollection中做删除操作你也许要查询该节点,但是一旦你找到了它你就可以使用ArrayCollection 的 removeItemAt() 方法,因为对于ArrayCollection来说索引总是合法的。

如果Tree的dataProvider是一个ArrayCollection的话,可以这样删除一个叶子节点:

 

程序代码

 

var node:Object = tree.selectedItem;

if( node == null ) return;

if( node.type != "employee" ) return;

var children:ArrayCollection = node.parent().children() as ArrayCollection;

for(var i:Number=0; i < children.length; i++) {

     if( children[i].name == node.name ) {

         children.removeItemAt(i);

         break; 

     }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值