views:

29

answers:

3

Lets say I have an ActionScript class: MyClass and that class has data in it. Now, lets say I want to iterate over that data using "for each":

var myData:MyClass = new MyClass();
myData.Populate(fromSource);

for each(var item in myData) {
  DoSomethingWith(item);
}

Of course, this does nothing, because MyClass is a custom class, and I haven't done anything special to it yet.

What do I need to do to MyClass to make it play nicely with "for each"? Can I hand it an iterator or an enumerator or something?

A: 

You should check out the Adobe livedocs page on for each ... in. They have your answer there.

"[for each ... in] Iterates over the items of a collection and executes statement for each item. Introduced as a part of the E4X language extensions, the for each..in statement can be used not only for XML objects, but also for objects and arrays. The for each..in statement iterates only through the dynamic properties of an object, not the fixed properties. A fixed property is a property that is defined as part of a class definition. To use the for each..in statement with an instance of a user-defined class, you must declare the class with the dynamic attribute."

Robusto
I don't think that answers my question. I don't want to iterate over my properties, I want to iterate over the data in my class, which could have thousands of items based on a lazy function. Simply declaring the class with the dynamic attribute is not enough.
Brian Genisio
+1  A: 

I believe you need to extend Proxy class and implement nextValue(index:int). It is used by for each.

alxx
+1 Yes! This got me to the correct answer. See my answer for a complete solution.
Brian Genisio
A: 

Ok, I figured it out.

@alxx helped me get to the answer. Here is a complete answer:

public class MyClass extends Proxy
{
    override flash_proxy function nextNameIndex (index:int):int {
        // This is the command to move to the next item or start over (index == 0)
        // return an incremented index when there is data
        // return 0 when you are done.
    }

    override flash_proxy function nextValue(index:int):* {
        // This is the command to get the data
        // The index that is passed in is the index returned in nextNameIndex
    }
}
Brian Genisio