views:

617

answers:

1

I have a Collection, and I want to remove all items that have a certain property set to true. I use a filterFunction to accomplish this. My question is, how can I add new items to the Collection that have that property set to true? The filterFunction is still applied, and the item is not added....

Do I have to iterate through the entire collection and remove items one at a time? I thought that that is exactly what refresh() does.

Thanks.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
    <mx:Script>
        private function hideSpecialItems():void
        {
            items.filterFunction = 
                function (item:Object):Boolean
                {
                    return item.isSpecial;
                }

            items.refresh();

            trace(items.length.toString()); // 2
        }

        private function addSpecialItem():void
        {
            items.addItem({name: "new Special Item", isSpecial: true});

            trace(items.length.toString()); // Item is added - returns 3
        }

        private function addNormalItem():void
        {
            items.addItem({name: "new Item", isSpecial: false});

            trace(items.length.toString()); // Item not added - returns 2
        }
    </mx:Script>

    <mx:ApplicationControlBar>
        <mx:Button label="Hide Items That Aren't Special" click="hideSpecialItems();" />

        <mx:Button label="Add a Normal Item" click="addNormalItem();" />

        <mx:Button label="Add a Special Item" click="addSpecialItem();" />
    </mx:ApplicationControlBar>

    <mx:ArrayCollection id="items">
        <mx:Array>
            <mx:Object name="item 1" isSpecial="{false}" />
            <mx:Object name="item 2" isSpecial="{false}" />
            <mx:Object name="item 3" isSpecial="{false}" />
            <mx:Object name="item 4" isSpecial="{true}" />
            <mx:Object name="item 5" isSpecial="{true}" />
            <mx:Object name="item 6" isSpecial="{false}" />
        </mx:Array>
    </mx:ArrayCollection>

    <mx:DataGrid dataProvider="{items}" />
</mx:Application>
+3  A: 

filterFunction doesn't actually remove the items from the ArrayCollection. It just hides them from the view. You can still see all the items in ArrayCollection.source property.

If you add new items while filterFunction is still applied, they too are subject to filtering.

To permanently remove items from a list, convert it to an Array and use Array#filter.

var newCollection:ArrayCollection = 
    new ArrayCollection(oldCollection.toArray().filter(myFilterFunction))
Chetan Sastry
Hey thanks for this answer. It works perfectly. Not very elegant, but it does exactly what I need in as few lines as possible.
Eric Belair