data provider:高级数据绑定

基于ListBase的flex组件从 data provider 获取数据。dataProvider提供了复杂数据类型,如Array,ArrayCollection,XML,XMLCollection等。dataProvider可以用mxml及AS两种方式定义。下面例子中的四个List展现同样的内容:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
    
<mx:Script>
        
<![CDATA[
            [Bindable]
            private var myArray:Array = ["a","b","c"];
            
            [Bindable]
            private var xml:XML = 
            <nodes>
                    <node label="a"/>
                <node label="b"/>
                <node label="c"/>
            </nodes>;
        
]]>
    
</mx:Script>
    
    
<mx:List dataProvider="{myArray}" width="50" height="200"/>
    
<mx:List dataProvider="{xml.children()}"  labelField="@label"  width="50" height="200"/>
    
<mx:List  width="50" height="200">
        
<mx:dataProvider>
            
<mx:Object label="a"/>
            
<mx:Object label="b"/>
            
<mx:Object label="c"/>
        
</mx:dataProvider>
    
</mx:List>
    
<mx:List   width="50" height="200" labelField="@label">
        
<mx:dataProvider>
        
<mx:XMLList>
                
<node label="a"/>
                
<node label="b"/>
                
<node label="c"/>            
        
</mx:XMLList>
            
        
</mx:dataProvider>
    
</mx:List>
    
</mx:Application>



如果使用Collection,可以保证数据同步并提供简单数据操作,比如排序和过滤。下面的例子演示了同步,排序和过滤:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" creationComplete="init()">
    
<mx:Script>
        
<![CDATA[
            import mx.collections.SortField;
            import mx.collections.Sort;
            import mx.collections.ArrayCollection;
            [Bindable]
            //private var myArray:Array =  ["c","b","a"];
            private var myArray:ArrayCollection = new ArrayCollection( ["c","b","a"]);
            private function sort(){                
                var sort:Sort = new Sort();
                sort.fields = [new SortField()];
                myArray.sort = sort;
                myArray.refresh();
                myArray.sort.fields = new Array();
            }
            
            private function filter(item:Object):Boolean{
                if("a"==item)
                    return false;
                else
                    return true;
            }
        
]]>
    
</mx:Script>
    
    
<mx:List dataProvider="{myArray}" width="50" height="200"/>
    
<!--<mx:Button label="add" click="myArray.push(myArray.length)"/>-->
    
<mx:Button label="add" click="myArray.addItem(myArray.length)"/>
    
<mx:Button label="sort" click="sort()"/>
    
<mx:Button label="filter" click="myArray.filterFunction=filter;myArray.refresh();"/>
</mx:Application>
posted @ 2007-12-07 17:27  心内求法  阅读(373)  评论(0编辑  收藏  举报