views:

398

answers:

3

I have a list object and I'm adding items to it with addItem through the dataProvider.

Before adding an item to the list I want to make sure it's not a duplicate. I've tried using indexOf on the dataProvider and it returns null. I've tried casting it to an array and it works, but always returns -1 even if the element exists in the dataProvider.

The only method I've been able to use seems a little hacky and I'd like to know if there is a better way to find an element in a dataProvider.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" styleName="plain" applicationComplete="init()">
    <mx:Script>
     <![CDATA[
      import mx.controls.List;
      [Bindable]
      public var testListArray:Array;


      public function init():void
      {
       testList.dataProvider.addItem('test');
       testList.dataProvider.addItem('banana');

       //search for element in dataProvider
       if(testList.dataProvider.toString().indexOf('banana') > -1)
       {
        trace('found');
       }

       //search for element in dataProvider
       if(testList.dataProvider.toString().indexOf('goat') === -1)
       {
        trace('not found');
       }
      }
     ]]>
    </mx:Script>
    <mx:List dataProvider="{testListArray}" x="260" y="204" id="testList" borderStyle="solid" borderColor="#000000"></mx:List>
</mx:Application>
A: 

If you want the list to change along with a change to the underlying data, you need to use an ArrayCollection instead of Array.

And it seems your problem is using the toString() function. It should be:

var arr:Array = testList.dataProvider as Array;
if(arr)
{
    if(arr.indexOf("banana") > -1)
        trace("found");
}

When you do dataProvider.toString(), you convert the array to a string, and then you search the string.

Also, Arrays do not have an addItem() function, you need to use push() instead. addItem is for ArrayCollections.

CookieOfFortune
Your variable "arr" will always be null. See julotlafrite for the reason.
bug-a-lot
+1  A: 

Even though you are feeding an array into the dataProvider property, the underlying dataProvider is always of type ArrayCollection and NOT Array. It supports arrays as input but converts them to ArrayCollection using the constructor:

ArrayCollection(source:Array)

You can use the following method:

ArrayCollection.contains(item:Object):Boolean

to ensure you are not adding a duplicate item.

julotlafrite
Thanks. That worked perfect! I used the contains method on the dataProvider and it acts just the way I want.
metric152
glad I could help!
julotlafrite
A: 

You can still use an Array but it will not be dynamic as with an ArrayCollection...

public function addToArray(item:String):void {
    if (testListArray.indexOf(item) < 0){
       testListArray.push(item);
       testList.dataProvider = testListArray;
     } 
}

you would only need to call this if you are adding data AFTER the creation of the list control.

AndrewB