Example: Using a simple data provider

The following sample code shows how you can use basic collection classes to represent and manipulate an Array for use in a control. This example shows the following features:

This example also shows the insertion's effect on the Array and the ArrayCollection representation of the Array:

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600" initialize="sortAC()">
    <mx:Script>
        <![CDATA[
            import mx.collections.*;
    
            // Function to sort the ArrayCollection in descending order.
            public function sortAC():void {
                var sortA:Sort = new Sort();
                sortA.fields=[new SortField("label")];
                myAC.sort=sortA;
                //Refresh the collection view to show the sort.
                myAC.refresh();
            }
            // Function to add an item in the ArrayCollection.
            // Data added to the view is also added to the underlying Array.
            // The ArrayCollection must be sorted for this to work.
            public function addItemToMyAC():void {
                myAC.addItem({label:"MD", data:"Annapolis"});
            }
        ]]>
    </mx:Script>

    <!-- An ArrayCollection with an array of objects -->
    <mx:ArrayCollection id="myAC">
        <!-- Use an mx:Array tag to associate an id with the array. --> 
        <mx:Array id="myArray">
            <mx:Object label="MI" data="Lansing"/>
            <mx:Object label="MO" data="Jefferson City"/>
            <mx:Object label="MA" data="Boston"/>
            <mx:Object label="MT" data="Helena"/>
            <mx:Object label="ME" data="Augusta"/>
            <mx:Object label="MS" data="Jackson"/>
            <mx:Object label="MN" data="Saint Paul"/>
        </mx:Array>    
    </mx:ArrayCollection>

    <mx:HBox width="100%">
        <!-- A ComboBox populated by the underlying Array object.
            This control shows that Array retains its original order
            and MD is inserted at the end of the Array. -->
        <mx:ComboBox id="cb2" rowCount="10" dataProvider="{myArray}"/>
        <!-- A ComboBox populated by the collection view of the Array. -->
        <mx:ComboBox id="cb1" rowCount="10" dataProvider="{myAC}"/>
        <mx:Button id="b1" label="Add MD" click="addItemToMyAC();"/>
    </mx:HBox>

</mx:Application>

Flex 2

 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/2/docs/00000502.html