Friday, November 14, 2008

Watch for Changes in an ArrayCollection

ArrayCollection is one of the most beautiful aspects of flex which makes it what it is. When dealing with ArrayCollections, one may want to have some kind of a callback when the items are changed.

This is how you can do it.

The magic lies in To detect a change just add a listener to the CollectionEvent.COLLECTION_CHANGE on the arrayCollection.

Even if your array collection is not bindable, this is a sure shot way to get notified of changes made to the array collection.

NOTE:The event will be triggered only when you add or delete items from the array collection and not when it is re assigned or re initialized  and not when you change the values of item within.


Here is the example:


<?xml version="1.0" encoding="utf-8"?>
     xmlns:mx="" layout="absolute">
            import mx.controls.Alert;
            import mx.collections.ArrayCollection;
            private var testAC:ArrayCollection = new ArrayCollection();
            private function setUpListeners():void {
            private function changeArrayCollection():void{               
                var obj:Object = new Object();
                //var temp:ArrayCollection = new ArrayCollection();
                //temp.addItem(new Object());               
                //testAC=temp; Will not trigger!
                //Note:testAC=new ArrayCollection(); Will not trigger!
            private function showChange(eve:CollectionEvent):void {
      "Collection Changed.Operation was of type->"+ eve.kind
                + "at location-> " + eve.location);
    <mx:HBox width="100%">
            <mx:FormItem label="name">
                <mx:TextInput id="nameInput" width="100">
            <mx:FormItem label="age">
                <mx:TextInput id="ageInput" width="100">
                <mx:Button label="change" click="changeArrayCollection()">

Hope it helps!!       






Bookmark and Share


Drobje said...

Thanks! This answers my question on what's going on. Nice example. However, unfortunately I need to detect when the ArrayCollection changed (just like in the NOTE section). How can I can

testAC=new ArrayCollection()

when it happens?

vikas said...

Thanks for the post.