Thursday, September 13, 2007

Working With Data in Flex: Using Cursor

Collections have ability to manipulate and sort data. This uses the concept of "cursor". All classes that implement ICursorView interface have the functionality. Eliminates need of complicated loops.

ArrayCollection implements ICursorView. Before we can use a cursor on it, we need to sort it. For this we use Sort and SortField classes and sort property of the collection.eg:

var cursor:IViewCursor = myArrayCollection.createCursor();
var sort1:Sort = new Sort();
var sortField1:SortField = new SortField("fieldToUse1");
var sortField2:SortField = new SortField("fieldToUse2",false,true,true);
sort1.fields=new Array(sortField1,sortField2);
myArrayCollection.sort = sort1;
myArrayCollection.refresh();

First we make a new instance of Sort. Then we need to make sort fields for the sort ie the property by which the whole collection should be sorted. SortField has one mandatory and three optional parameters with default value of false. First is name of property on which to sort. Second if sort should be case sensitive. Third if it should be descending sort. Fourth if it should be a numeric sort. A Sort can have several fields given to it in an Array. It uses them in the order to sort. In this case it would first sort by field1 and then by field2. Then this sort is given to the collection and refresh method called to sort.

From this point we can various methods on the cursor. The cursor will find using the fields specified for sorting. eg. cursor.findFirst(obj); will see if the obj Object already exists in myArrayCollection and will return true or false accordingly. The search will happen using the sortfield ie field of the Object will be matched with those in the list. We also have findLast and findAny methods. cursor.current gives the current object being pointed to. Dont forget to cast the object obtained. Finally there is the remove() method to remove the object to which the cursor is pointing to.

Questions:
  1. How do you sort/manipulate data in flex collections?
  2. With an example illustrate how you would sort a collection?
  3. How would you ensure that a field is used to sort the collection is case insensitive, ascending and numeric?
  4. What is the use of a cursor?

No comments: