Our sort code above successfully connects the Sort object to our ArrayCollection. This code needs to be executed once before we can make greater use of it. To make this possible, we will create a new function that runs after the application has been created. We will take advantage of the creationComplete event that is triggered once the application is created. We will modify the Application Tag in the following way: <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="100%" height="100%" creationComplete="init()"> Notice the newly-added creationComplete="init()". This will cause the init function to be called when the application is created. Here is the init function along with some Sort Object declaration (in public scope): import mx.collections.Sort; import mx.collections.SortField; // create our sort object public var sort:Sort = new Sort();
// connect the sort object to the ArrayCollection public function init():void{ sort.fields = [new SortField("label", true)]; computersCollection.sort=sort; } This code will not sort the list immediately because the creationComplete event is triggered after the controls on the screen have been displayed. What you will see is the natural order as listed in our dataProvider. To cause the list to be sorted we will add a sort Button to our UI. We'll add this code to our MXML after the <mx:List> tag: <mx:HBox> <mx:Button label="Toggle Sort Order" click="toggleOrder(event)"/> </mx:HBox> Our button has a click event which refers to the following function: public function toggleOrder(event:MouseEvent):void{ sort.reverse(); computersCollection.refresh(); }
The toggleOrder function calls the sort object's reverse property. Next, we refresh the ArrayCollection so that it will re-apply the sorting algorithm. That is all that is needed to switch the sort order from ascending to descending order. So there you have it. We've successfully created a Flex application which can filter a list of items based on user input as well as sort them when the user initiates it. Flex/ActionScript provides easy to use methods that allow this type of processing to be performed with a minimum amount of code. Our Flex application was a mere 73 lines of code, which included the list items (they would normally be pulled from an external source). You can see the full Flex app running at: http://www.reefkeysoftware.com/blog/sort_filter Resources http://livedocs.adobe.com/flex/3/langref/mx/collections/ArrayCollection.html http://livedocs.adobe.com/flex/3/langref/mx/collections/Sort.html http://livedocs.adobe.com/flex/3/langref/mx/collections/SortField.html http://livedocs.adobe.com/flex/3/html/help.html?content=mxmlSyntax_3.html http://livedocs.adobe.com/flex/3/langref/String.html http://livedocs.adobe.com/flex/3/langref/mx/core/Application.html#eventSummary
blog comments powered by Disqus |
|
|
|
|
|
|
|