I just finished writing my own collecion class, and i'd really like to make it iterable with the for each or the simple for construct, or just to access elements with the collection[key] notation.
I've written a getElementAt(index):MyOwnElement
function, but using it, is not as sexy as using the square brachets, don't even let me start on iterating..
Is there any way?
You should take a look at mx.utils.Proxy
-- subclassing your collection class from that (and setting it as dynamic) might give you access to some of the functionality you want (or at least something that's close enough.)
For example, here's an excerpt from the documentation of the nextValue()
method:
"Allows enumeration of the proxied
object's properties by index number to
retrieve property values. However, you
cannot enumerate the properties of the
Proxy class themselves. This function
supports implementing for...in
and for
each..in
loops on the object to
retrieve the desired values."
There's a pretty good article on implementing the iterator pattern in AS3 here
You can not override operator in AS3.
I think you may change 'getElementAt' to a short name likes 'at':)
or assgin getElementAt to a temp variable....
Depends on the internal structure of your collection. If your collection is stored as an Array then you can use properities to achieve a square bracket effect:
/*** MyCollection class ***/
private var elementHolder : Array;
public function get getElementAt() : Array{
return elementHolder;
}
/*** Some other class******/
public function main() : void{
trace("Element at 3: " + myCollection.getElementAt[3] );
}
If your collection is not stored in an array maybe you can convert it to an array (like the java Collection's toArray() method).
for example, if your collection is a linked list:
/*** MyCollection class ***/
public function get getElementAt() : Array{
var temp : Array = new Array();
while( node.next != null{
temp.push( node );
}
return temp;
}
/*** Some other class******/
public function main() : void{
trace("Element at 3: " + myCollection.getElementAt[3] );
}