i'm trying to assign a parent's variable from the parent's child
//Parent
public class Main extends Sprite
{
public var selectedSquare:Sprite;
public function Main()
{
//inits and adds new Square child class to display list
}
...
-------
//Child
public function dragSquare(evt:MouseEvent):void
{
Sprite(parent).selectedSquare = this; //evil doesn't work!
parent.addChild(this);
this.startDrag();
}
i'm receiving this error, but i'm casting parent from displayObjectContainer to a Sprite so i have no idea why it's not working.
1119: Access of possibly undefined property selectedSquare through a r开发者_如何学Goeference with static type flash.display:Sprite.
You should cast parent as a Main rather than a Sprite, since a Sprite won't have any references to a "selectedSquare". If Main were to extend MovieClip, this wouldn't be a problem, since MovieClips can have dynamically created references.
Proposed modification to child function:
public function dragSquare(evt:MouseEvent):void
{
(parent as Main).selectedSquare = this;
parent.addChild(this);
this.startDrag();
}
Another reason that this may not work is that you're attempting to use the parent
property right before adding the child to the parent's display list.
Sprite(parent).selectedSquare = this;
parent.addChild(this);
That second line is what worries me. In this code, the current object (this
) must already be added as a child to the parent object (Main
) for the first line to work properly. So, either the current object is not yet a child of the parent object, in which case you need to revise your code.
Or, the second line is unnecessary (because this
is already a child of Main
, that's why this.parent
, or just parent
, works as expected).
I believe, though, that your code is probably set up well. You just don't need that second line, as it's completely redundant.
I hope that helps! Let me know if you want me to clarify anything.
(This is, of course, assuming you didn't already know all of this and aren't doing some sort of insane, arcane, weird magic with the redundant addChild
call. You never can tell with magicians!)
精彩评论