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>
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.