The process we will use to filter the list is quite simple. Flex and ActionScript have made this job easy for us by providing the filterFunction attribute of the ArrayCollection. This attribute points the ArrayCollection to a function that we will write. The function determines which of the elements of the collection will be displayed and which elements will not be displayed. The function is called once for every item in the list. The function must has a Boolean return type which translates TRUE to display the object and FALSE to NOT display this object. Here is what our filter function will look like: public function filter(item:Object):Boolean{
var tmpString:String = new String(item);
// If there is nothing is the search box if (search.text==""){ return true; }
// if the contents of the search box // is a sub string of this item if (tmpString.indexOf(search.text)!=-1){ return true; }
return false; } Let's break this down. The item is passed to our function by the ArrayCollection as an Object. The first thing that our function does is create a new String object out of the item being tested for display. We do this because we want to make use of the some the string methods (indexOf). Next, we check to see if our search TextInput is blank. If it is, then we should not filter anything. In this case, we simply return TRUE for all elements. If the search TextInput DOES have text in it, we would have to continue execution of this function in order to see if the contents of the search TextArea is a substring of the item being tested for display. If the search text turns out to be a substring of the item, we would return TRUE, thereby causing the item to be displayed. At the start of the application, all items are display; however, if we were to type into our TextInput, nothing would change in our list. This is because we need to tell the the ArrayCollection to refresh itself when a character has been pressed in the search box. To do this, we add the following event to the search input: <mx:TextInput id="search" width="100%" keyUp="computersCollection.refresh()"/> Refreshing the ArrayCollection effectively calls the filterFunction again -- once per item. Here is a look at the completed application: ![]() In the example image above example, notice that only items with the word Laptop are displayed.
blog comments powered by Disqus |
|
|
|
|
|
|
|