Posted in AIR, Apple, Flex
11/12 2009

Using the Flex IViewCursor to Manage an ArrayCollection

One of the nice things about the Flex framework is the various utility classes that make it so much easier for you to accomplish your development tasks than you’d be able to without them. One such class, in my opinion, is mx.collections.IViewCursor. What this class does is to define an interface for enumerating a collection view (ie, ArrayCollection) both forwards and backwards. Using this construct, you can avoid having to use for.. loops to examine the collection.

Here’s a quick example of a fictitious auto maker that’s tasked us to update some info related to one of its auto dealers after receiving the quarterly sales report:

var carDealers:ArrayCollection;
var dealerCursor:IViewCursor;
var vehicleCursor:IViewCursor;
 
var affectedDealer:CarDealer;
var targetVehicle:Car;
var targetVehicleIndex:Number;
 
var dealerIdFromSale:String = 'XXXXXXXX-XXXX-XXXX-XXXXXXXXXXX';
var vinNumberFromSale:String = 'XXXXXXXXXXXXXXXXX';
 
dealerCursor = carDealers.createCursor();
 
// iterate through the list of dealers
while (!dealerCursor.afterLast)
{
  if (dealerCursor.current.dealerId == dealerIdFromSale)
  {
     affectedDealer = CarDealer( dealerCursor.current );
 
     // create a cursor to iterate over the dealer's inventory
     vehicleCursor = affectedDealer.inventory.createCursor();
 
     // iterate over the inventory
     while (!vehicleCursor.afterLast)
     {
        if (vehicleCursor.current.VIN == vinNumberFromSale)
        {
           // a match was found so now we need the
           // index of this vehicle in the ArrayCollection
           targetVehicle = Car( vehicleCursor.current );
           targetVehicleIndex = affectedDealer.inventory.getItemIndex( targetVehicle );
 
           // since the sale was successful, we can safely
           // remove the vehicle from this dealer's inventory
           affectedDealer.inventory.removeItemAt( targetVehicleIndex );
        }
 
        vehicleCursor.moveNext();
     }
  }
 
  dealerCursor.moveNext();
}

In a few lines of code, we’re able to create some very readable and manageable logic to complete the task of updating the inventory. And, you may notice that we also iterated over not one, but two ArrayCollection instances with our mighty IViewCursor. One additional thing to note is the use of the moveNext() method. It’s important that you instruct the cursor that it’s OK to advance even though you’ve found what you’re looking for; otherwise, plan on some serious hang time. I mean it is still a while..loop after all!

:D

This Post tags: , ,

 

USER COMMENTS

Track comments via RSS 2.0 feed. Feel free to post the comment, or trackback from your web site.

Currently there are no comments related to article "Using the Flex IViewCursor to Manage an ArrayCollection".

Get Adobe Flash playerPlugin by wpburn.com wordpress themes