Playing nicely with "for each" in ActionScript?
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) {
DoSomethingW开发者_Go百科ith(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?
I believe you need to extend Proxy class and implement nextValue(index:int)
. It is used by for each
.
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
}
}
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."
精彩评论