views:

39

answers:

2

Task:

Design a class that is a collection of other objects and could be used in for each (..)

public class Cards
{
    public function add( $Card : Card ) { ... }
}

//...

var $Cards:Cards = new Cards();
//...
for each ( var $Card:Card in $Cards) {
    // do things
}

My first attemt was to use Array class as parent:

public class Cards extends Array { ... }

This works great but Cards class inherits lots of Array's public methods that shouldn't be visible in Cards objects like sort(), push(), forEach(), etc

Second attempt was to define base class as dynamic:

public dynamic class Cards { ... }

This works, but in this case I should define every child class as dynamic too:

public dynamic class Cards { ... }
...
var $Cards:Cards = new Cards();
$Cards.add( new Card() ); // works well

but

public class Player_Cards extends Cards { ... }
...
var $PlayerCards:Cards = new Player_Cards();
$PlayerCards.add( new Card() ); // error, Player_Class should be defined as dynamic too   

Interesting thing is that if I use Array class as parent I shouldn't define child classes as dynamic

So, the question is: Is it possible to design a collection class in AS3 that could be used in for each (...) and will not contain any unnessary methods (like from Array class)?

A: 

You should be able to subclass Object and implement propertyIsEnumerable.

thenduks
A: 

You can do this extending the Proxy class.

Check this question for some pointers on how to do this.

Juan Pablo Califano
Very cool! Had not seem that before.
thenduks
@thenduks. I though the same when I first learned about proxy's existence. (Though I never really used it in a real project, just played around a bit with it).
Juan Pablo Califano
Yes! Exactly what I was looking for. Many thanks!