Hi I have a custom class that extends Sprite, that controls positioning on the stage. I would like the class that manages the stage to be able to take any sprite that is added to the stage and convert it to custom class type, ie wrap it so that the managing class can position a native sprite accordingly.
Does anyone know if it is possible to do something like the following
var managed:managedSprite = new managedSprite(nativeSprite);
where the managedSprite extends the Sprite class? I don’t want to have to composite in a reference to the sprite if at all possible in order to prevent the overhead associated with the managedSprite already extending Sprite.
Is there anyway using reflection (perhaps the commons.reflection library)?
Thanks
You can add an event listener to the stage and use
Event.ADDEDto get a reference to any display object added anywhere in the display list.Then simply type cast if the added item is a subclass of
ManagedSprite(BTW, the convention is to start your class names with an uppercase letter):EDIT
I think I only just understood your question: You are not trying to do an actual type cast – which would require your class hierarchy to be already set up, i.e. you’d have to have extended the ManagedSprite class already – but to add functionality at runtime!
I would strongly discourage you from trying to do deep copies or such – it will be heavy on performance, depending on how many sprites you are going to add, and you will no longer have your compiler to help you prevent errors.
Rather, see if you can’t favor composition over inheritance: Create a kind of “proxy” class for the sprite, let’s call it
ManagedSpriteProxy, which implements all the methods you would call on ManagedSprite, but forwards all the actual manipulations to its `managedSprite’ property. Then use the event handler I outlined above to create the proxy objects and attach the respective sprites: