XMLListCollection
XMLListCollection特点就是
- 给组件(component)做dataProvider用的。
- 为用户提供了collection方法,可以像ArrayCollection操作Array一样,XMLListCollection操作XMLList
下面来看看代码:
<?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:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.events.FlexEvent;
[Bindable]
private var xmlListCollection:XMLListCollection ;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
xmlListCollection = new XMLListCollection(xml1)
trace("---------------------");
trace(xml1);
}
]]>
</fx:Script>
<fx:Declarations>
<fx:XMLList id="xml1">
<node age="18" label="tomcat" >
<item label="5.0" />
<item label="6.0" />
<item label="7.0" />
</node>
<node age="20" label="java" >
<item label="1.5" >
<node label="xx" />
<node label="yy" />
<node label="zz" />
</item>
<item label="1.6" />
<item label="1.7" />
</node>
<node age="30" label="webLogic" >
</node>
</fx:XMLList>
</fx:Declarations>
<mx:Tree id="tree" dataProvider="{xmlListCollection}" labelField="@label" width="500" height="100%">
</mx:Tree>
</s:Application>
注意:
- XMLListCollection对象的创建,一定是基于一个XMLList对象。
- xml的标签,只要有清晰层级关系就好,标签名称可以不一样。
- 这里面为了方便,让每个标签都有label属性。
- tree组件,为了指定显示的label,从而设置了labelField属性。
- 如果dataProvider的数据源是XMLListCollection, 引用其xml的属性,需要使用@ (labelField="@label")
运行截图:
好吧:
tree组件的set dataProvider(value:Object)方法,内部对传入的数据源,做了包装。源代码如下:
override public function set dataProvider(value:Object):void
{
// in all cases save off the original
if (_rootModel)
_rootModel.removeEventListener(
CollectionEvent.COLLECTION_CHANGE,
collectionChangeHandler);
// handle strings and xml
if (typeof(value)=="string")
value = new XML(value);
else if (value is XMLNode)
value = new XML(XMLNode(value).toString());
else if (value is XMLList)
value = new XMLListCollection(value as XMLList);
if (value is XML)
{
_hasRoot = true;
var xl:XMLList = new XMLList();
xl += value;
_rootModel = new XMLListCollection(xl);
}
//if already a collection dont make new one
else if (value is ICollectionView)
{
_rootModel = ICollectionView(value);
if (_rootModel.length == 1)
_hasRoot = true;
}
else if (value is Array)
{
_rootModel = new ArrayCollection(value as Array);
}
//all other types get wrapped in an ArrayCollection
else if (value is Object)
{
_hasRoot = true;
// convert to an array containing this one item
var tmp:Array = [];
tmp.push(value);
_rootModel = new ArrayCollection(tmp);
}
else
{
_rootModel = new ArrayCollection();
}
//flag for processing in commitProps
dataProviderChanged = true;
invalidateProperties();
}
可见,flex的component对传入的数据源,做了很强大的容错机制。