The following example shows how you can detect when a Flex ArrayCollection has changed (items added, removed, refreshed) by listening for the collectionChange event.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/05/14/determining-when-an-arraycollection-changes-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.utils.ObjectUtil;
            import mx.controls.dataGridClasses.DataGridColumn;
            import mx.events.CollectionEvent;

            private function arrColl_collectionChange(evt:CollectionEvent):void {
                callLater(addTheItem, [evt]);
            }

            private function arrCollAddItem():void {
                arrColl.addItem({data:new Date()});
            }

            private function addTheItem(evt:Event):void {
                eventsArrColl.addItem(evt);
            }

            private function arrCollRemoveItem():void {
                if (arrColl.length > 0) {
                    arrColl.removeItemAt(0);
                }
            }

            private function dataGridColumn_labelFunc(item:Object, col:DataGridColumn):String {
                return ObjectUtil.toString(item[col.dataField]);
            }
        ]]>
    </mx:Script>

    <mx:ArrayCollection id="eventsArrColl" />
    <mx:ArrayCollection id="arrColl"
            collectionChange="arrColl_collectionChange(event);" />

    <mx:Model id="columnModel">
        <columns>
            <bubbles>{bubblesCheckBox.selected}</bubbles>
            <cancelable>{cancelableCheckBox.selected}</cancelable>
            <currentTarget>{currentTargetCheckBox.selected}</currentTarget>
            <eventPhase>{eventPhaseCheckBox.selected}</eventPhase>
            <items>{itemsCheckBox.selected}</items>
            <kind>{kindCheckBox.selected}</kind>
            <location>{locationCheckBox.selected}</location>
            <oldLocation>{oldLocationCheckBox.selected}</oldLocation>
            <target>{targetCheckBox.selected}</target>
            <type>{typeCheckBox.selected}</type>
        </columns>
    </mx:Model>

    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Add item to ArrayCollection"
                emphasized="true"
                click="arrCollAddItem();" />
        <mx:Button label="Remove item"
                click="arrCollRemoveItem();" />
        <mx:Button label="Refresh items"
                click="arrColl.refresh();" />

        <mx:Spacer width="100%" />

        <mx:PopUpButton label="Toggle DataGrid columns"
                openAlways="true">
            <mx:popUp>
                <mx:Form styleName="plain"
                        backgroundColor="white">
                    <mx:FormItem label="bubbles:">
                        <mx:CheckBox id="bubblesCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="cancelable:">
                        <mx:CheckBox id="cancelableCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="currentTarget:">
                        <mx:CheckBox id="currentTargetCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="eventPhase:">
                        <mx:CheckBox id="eventPhaseCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="items:">
                        <mx:CheckBox id="itemsCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="kind:">
                        <mx:CheckBox id="kindCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="location:">
                        <mx:CheckBox id="locationCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="oldLocation:">
                        <mx:CheckBox id="oldLocationCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="target:">
                        <mx:CheckBox id="targetCheckBox"
                                selected="true" />
                    </mx:FormItem>
                    <mx:FormItem label="type:">
                        <mx:CheckBox id="typeCheckBox"
                                selected="true" />
                    </mx:FormItem>
                </mx:Form>
            </mx:popUp>
        </mx:PopUpButton>
    </mx:ApplicationControlBar>

    <mx:VDividedBox width="100%" height="100%">
        <mx:List id="list"
                dataProvider="{arrColl}"
                labelField="data"
                width="50%"
                rowCount="5" />
        <mx:DataGrid id="dataGrid"
                dataProvider="{eventsArrColl}"
                itemRenderer="mx.controls.Label"
                width="100%"
                height="100%">
            <mx:columns>
                <mx:DataGridColumn dataField="bubbles"
                        visible="{columnModel.bubbles}" />
                <mx:DataGridColumn dataField="cancelable"
                        visible="{columnModel.cancelable}" />
                <mx:DataGridColumn dataField="currentTarget"
                        visible="{columnModel.currentTarget}" />
                <mx:DataGridColumn dataField="eventPhase"
                        visible="{columnModel.eventPhase}" />
                <mx:DataGridColumn dataField="items"
                        labelFunction="dataGridColumn_labelFunc"
                        visible="{columnModel.items}" />
                <mx:DataGridColumn dataField="kind"
                        visible="{columnModel.kind}" />
                <mx:DataGridColumn dataField="location"
                        visible="{columnModel.location}" />
                <mx:DataGridColumn dataField="oldLocation"
                        visible="{columnModel.oldLocation}" />
                <mx:DataGridColumn dataField="target"
                        visible="{columnModel.target}" />
                <mx:DataGridColumn dataField="type"
                        visible="{columnModel.type}" />
            </mx:columns>
        </mx:DataGrid>
    </mx:VDividedBox>

</mx:Application>

View source is enabled in the following example.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

10 Responses to Determining when an ArrayCollection changes in Flex

  1. Vital says:

    Hi Peter, sorry i couldn’t find how to contact you
    so i’m writing here

    first of all thanks a lot for this website )

    i started getting in flex a couple of weeks ago,but it turned out that there is practically no inforamtion about this technology in russian (not a single book even!)

    lots i gained from your blog and adobe live docs

    so i decided to start a blog http://flexcookbook.ru similar to yours (but in russian)
    for people that would like to know more abt flex but can’t read english

    i have a couple of questions:
    is that ok to publish your articles (translated into russian) on my blog’s pages (providing back link to original)?

    can we exchange links?

  2. peterd says:

    Vital,

    Yeah, this blog has a Creative Commons License, so you’re free to use/modify/republish the examples as long as you link back to this site.

    And yes, I will add a link to your site at http://blog.flexexamples.com/links/ (right under the Chinese FlexExamples link).

    Thanks,
    Peter

  3. Vincent Lesieux says:

    Hi Peter, could you help me to solve this problem if possible :

    I have got a dataGrid that is populated with a dataprovider generated by a httpservice whose id is send.

    I have also a button that makes a refresh of the dataGrid because it applies the send() function when it is clicked.

    Then the previous selectedItem of the dataGrid disappears.

    I would like to keep in memory the selectedItem just before clicking the button so that the user doesn’t need to select it once again because only one column of the dataGrid is changed.

    I hope you have understood my problem.

    Thank you.
    Vincent

  4. PSamanth says:

    Hello

    Hey Thanks for this PopUpButton Tutorial, I have a small Issues, the above code works fine when I am using in the main application, But When I am using in the Sub files (src/com/folder), not able to get the PopUpButton button control(the dropDown does not work at all)

    Is there anything we need to import for the Subfiles

    Please help me..

    Thanks in Advance
    PSamanth

  5. peterd says:

    PSamanth,

    Can you please file a bug at http://bugs.adobe.com/flex/ (log it against the Flex SDK project and mx:PopUpButton feature) and include a simple, reproducible test case?

    Thanks,
    Peter

  6. PSamanth says:

    Thanks a lot, it had Fixed in the latest, I had upgraded with the latest build and it work fine

    Thanks,
    PSamanth

  7. Tom says:

    HI Peter,

    Do you know how to use the others ArrayCollection such as Update? My probleme is I would like to know when objects of my ArrayCollection are modified.

    Cheers

  8. alaeddin says:

    dear
    could you please tell me how to show the value of field inside the each currentTarget items. In your sample the CurrentTarget is object . I want to know how can I access to each field of this object when the arraycollection is look like your array I mean the collection of data and object. thank you so much

  9. ana emi says:

    that’s perfect post.
    could you please tell me if it possible to put an arraycolection to an array.

  10. Wilson Silva says:

    @ana emi

    The Array is used compositionally in the ArrayCollection and is a wrapper around the Array that implements the List and Collection functionality. The Array can be pulled from the collection via:

    var array:Array = [];
    var arrayCollection:ArrayCollection = new ArrayCollection();

    array = arrayCollection.source;

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree