views:

1182

answers:

2

I'm trying to create a collection class in Flex that is limited to housing a specific type of data that i am using (an interface). I have chosen not to extend the ArrayCollection class as it's too generic and doesn't really give me the compile time safety that i'm after. In it's simplistic form my collection contains an array and i manage how objects are added and removed, etc.

What i really want to be able to do is use these collections in for each loops. It definitely doesn't seem as straight forward as say c# where you just implement IEnumerable and IEnumerator (or just using the generic Collection). Is there a way to do this in action script and if so any info on how it is achieved?

Cheers

+2  A: 

Take a look at Vector<>. That is about as best as you can go for a typed collection in Flex (4 onwards). However, you will need to implement your own class otherwise. One way, it seems, is to use the Iterator Pattern.

Also, take a look at this SO post.

dirkgently
Yeah i'm programing for flash 9 so i can't use the Vector object. There must be a way to implement some sort of iterator pattern in flex as the ListCollectionView classes can be used in for each loops.
James Hay
Sure, take a look at Brian Heylin's answer to his own question.
dirkgently
Also, Vector.<> is available in Flex 3 as long as you are targetting Flash 10.
Richard Szalay
+2  A: 

You need to extend the Flash Proxy class. Extending Proxy allows you to alter how 'get' and 'set' work, as well as 'for..in' and 'for..each' loops. You can find more details on the Livedocs.

Here's an example for your issue:

package
{
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    public class EnumerableColl extends Proxy
    {
     private var _coll:Array;

     public function EnumerableColl()
     {
      super();
      _coll = [ 'test1', 'test2', 'test3' ];
     }

     override flash_proxy function nextNameIndex( index:int ):int
     {
      if ( index >= _coll.length ) return 0;
      return index + 1;
     } 


     override flash_proxy function nextValue( index:int ):*
     {
      return _coll[ index - 1];
     }

    }
}
jmreidy
sweet... just what i was looking for, cheers to the both of you
James Hay