I cannot reference parent in my constructor method - actionscript-3

public function Browser(){
var chrome:chromeicon = new chromeicon();
this.parent.addChild(chrome);
chrome.y = 745;
chrome.x = 220;
}
I notice that I cannot reference the parent of the class in the constructor method or any method that is instantiated when I add the object. There must be a way around this problem, but since I'm new to oop I don't know it.

It's because a "parent" refers to parent on list of displayed objects. It means that as long as this object is not added as a child to other object, it has no parent, I'm not sure if they need to be added to stage also. You can go around this problem by adding to constructor a listener:
this.addEventListener(Event.ADDED_TO_STAGE, _myFunction);
and then construct a function:
private function _myFunction(e:Event) :void {
this.removeEventListener(Event.ADDED_TO_STAGE, _myFunction);
// here you will be sure that your object has a parent that you can refer to, that will be a parent on the display list.
}

Related

Using .stage not giving desired result

I make a global variable equal to a movieclip
A function gets run with an if statement checking if [x] movieclip exists, if it doesn't add it.
Despite the MovieClip being on the stage it continues using the if statement.
Document class
public static var skinHolder:MovieClip = new test;
Seperate Class (function runs every frame)
function animHandler():void
{
if (! Game.skinHolder.stage)
{
// if its not on the stage we add it to the stage
addChild(Game.skinHolder);
}
}
The stage is not set immediately after a MovieClip is added, usually it happens on the next frame.
It is an odd way to check if an object exist though, you should do something like this:
private var mySkinHolder:MovieClip;
if (!mySkinHolder)
{
// if it not exist we add it to the stage
mySkinHolder = addChild(new test());
}
I don't completely understand your structure, but to check if a DisplayObjectContainer (MovieClip in your case) has a specific child, you can use the contains() method.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#contains()
if (!contains(Game.skinHolder)) {
addChild(Game.skinHolder);
}

AS3 delete object when clicked

I want to set an object to null when it's being clicked and I'm trying to implement this code:
public function onClick(evt:MouseEvent):void{
var thisPatient = evt.target;
thisPatient = null;
}
However, the element is still on the stage.
public function onClick(evt:MouseEvent):void{
var thisPatient = evt.target;
(thisPatient as DisplayObject).parent.removeChild(thisPatient);
//or if thisPatient is this
parent.removeChild(this);
}
But it's bad practive to allow children to remove itself. More right solution is dispathing event because parent must decide remove or not remove child.
public function onClick(evt:MouseEvent):void{
dispatchEvent(new Event("removeMe", true));
}
//parent's code...
child.addEventListener("removeMe", removeHandler);
Setting it to null doesn't suffice. You also have to remove it from its parent container using removeElement() or removeChild() depending on what kind of container you're using.
You just have to do removeChild(thisPatient) and if you put the object inside another object you have to do parent.removeChild(thisPatient)!
In my experience, Register for a events object, you must remove all of the events. all events will be removed completely manually. removeChild on the object that will not release all of the events. the removeChild but, finely memory leak occurs. This is because you did not remove the event. Before you remove an object, you must remove the event.

AS3 Display Object Trouble

I'm making a game in AS3. When I add an enemy to the game screen, later on I have to remove it when it dies. But I keep getting this:
[Fault] exception, information=ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
But I clearly add the enemy to the gamescreen. Could this be from passing the enemy through a bunch of functions or something?
This means that you try to remove the MovieClip (or Sprite or so) from a DisplayObjectContainer that is not its parent.
You have to be sure to call the removeChild() Method on the right DisplayObjectContainer.
For instance:
var myChild:MovieClip = new MovieClip();
var holder:MovieClip = new MovieClip();
holder.addChild(myChild);
so when you want to remove the child you have to call the removeChild Method on the holder.
holder.removeChild(myChild);
If you call removeChild() on for instance the stage you will get an error because the stage does not hold myChild as a child of itself.
So double check if you call removeChild on the right container.
PS: Sample code is always easier to debug
When dealing with the timeline, it's difficult sometimes to keep track of an object's scope , in which case you can always call the method from the object's parent property.
child.parent.removeChild( child );
if you're coding in FlashDevelop & for some reason , don't wish to or can't keep track of the parent , you could implement a couple of methods to add and remove your object from the display list, practically delegating adding & removing to the object...
in your object class , you could do the following...
private var container:DisplayObjectContainer;
public function addToDisplayList( container:DisplayObjectContainer ):void
{
this.container = container;
container.addChild( this );
}
public function remove():void
{
if( container != null )
container.removeChild( this );
}
Then you can simply do this:
var child:MovieClip = new MyObject();
child.addToDisplayList( whatever );
//later...
child.remove();

Is there a way for listening for changes in flash.display.DisplayObjectContainer numChildren property?

I want to run some code whenever a DisplayObject is added as a child to a DisplayObjectContainer.
Or to put in other words, to catch the addedToStage event of all DisplayObjects, even ones I don't know about.
Is it possible? and if not, any ideas on how to do something similar?
An 'added' event is dispatched whenever a child display object is added to the display list via addChild() or addChildAt(). In the DisplayObjectContainer class add the listener:
addEventListener(Event.ADDED, onAdded);
and the handler:
private function onAdded(e:Event):void
{
trace('number of children is now ' + numChildren);
}
Using Event.ADDED_TO_STAGE on stage Object and setting useCapture to true.
More info on event here
Example:
function onAdded(e:Event):void{
trace(e.target.toString()); //use target to get the Object added
}
stage.addEventListener(Event.ADDED_TO_STAGE, onAdded, true); // set capture to true
I don't know if there is a built in way to do this.
Alternatives include the obvious,
private var _num_children:Number = 0;
addEventListener(Event.ENTER_FRAME, _checkChildren, false, 0, true);
private function _checkChildren($evt:Event):void {
if (this.numChildren != _num_children) {
_num_children = this.numChildren;
// There was a child (or more) added in the last frame execution
}
}
However, this seems like a more elegant solution...
public function _addChild($do:DisplayObject) {
$do .addEventListener(Event.ADDED_TO_STAGE, _childAdded);
addChild($do );
}
private function _childAdded($evt:Event) {
// do whatever with $evt.target
}
The difference here, is the _childAdded will get fired for each and every child added via _addChild method. This means if you are doing some costly code execution you will be doing it once for each child instance.
If you use the first method, you are only calling the method once per frame, and if 10 images are added on a single frame, then it will only run once.

as3 - dispatchEvent from a parent swf to a child swf

I have one main "parent" swf that loads several other swfs. If something happens in the main swf I need to tell one of the child swfs about it.
This seems to work well the other way around. Any of the children can simply dispatchEvent(), and I can set up the main swf to listen for the event. However, I can't get the child swf to catch any events dispatched by the parent. How is it done?
OK, so if you know most of this already, my apologies... but it seems a pretty common issue and isn't immediately obvious.
In AS3 events dispatched by objects on the display list can be listened for as they bubble up the display list hierarchy without needing to specify the originating object. (Assuming of course that the event has its bubbling property set to true). Hence the Document Class (the old concept of _root) can respond to mouse clicks from any display object, no matter how deeply nested, with addEventListener(MouseEvent.CLICK, _onMouseClick)
In any other situation - e.g. bubbling is set to false, the broadcaster is not an InteractiveObject on the display list or, (as in your case) the listener is lower than the broadcaster in the display list hierarchy - the object broadcasting the event must be specifically listened to: fooInstance.addEventListener(Event.BAR, _bazFunc) as opposed to just addEventListener(Event.BAR, _bazFunc)
Basically you need to pass a reference to the parent object to your child swf so that it can then attach event handlers to it.
One method is to dispatch an event from the child to the parent class via the display list (once the child has loaded and fully initialised). The parent uses the event.target property of this event to reference the child and set a parentClass variable on it. This can then be used to attach listeners:
package {
class ChildClass
{
private var __parentClass:ParentClass;
// EventID to listen for in ParentClass
public static const INITIALISED:String = "childInitialised";
// Constructor
function ChildClass()
{
// Do initialising stuff, then call:
_onInitialised();
}
private function _onInitialised():void
{
// Dispatch event via display hierarchy
// ParentClass instance listens for generic events of this type
// e.g. in ParentClass:
// addEventListener(ChildClass.INITIALISED, _onChildInitialised);
// function _onChildInitialised(event:Event):void {
// event.target.parentClass = this;
// }
// #see mutator method "set parentClass" below
dispatchEvent(new Event(ChildClass.INITIALISED, true);
}
public function set parentClass(value:ParentClass):void
{
__parentClass = value;
// Listen for the events you need to respond to
__parentClass.addEventListener(ParentClass.FOO, _onParentFoo, false, 0, true);
__parentClass.addEventListener(ParentClass.BAR, _onParentBar, false, 0, true);
}
private function _onParentFoo(event:Event):void
{
...
}
}
}
Dispatching a custom ChildSWFEvent - i.e. instead of using a class-defined constant as above - will make this a more flexible solution since the ParentClass instance can listen for a common ChildSWFEvent.INITIALISED event broadcast by any child swf with contextually useful information passed as an additional parameter.
When you load a child swf (Main.swf) in an parent swf (Index.swf), keep a reference in a field variable or class variable
fldMain = BulkLoader.getLoader("Index").getContent("Main.swf") as DisplayObject;
this.addChild(fldMain);
(i'm using BulkLoader to load any content)
It's a good practice to wait with dispatching events until the child is added (ADDED_TO_STAGE event)
When I want to dispatch an event to my child I just say:
fldMain.dispatchEvent(new CustomEvent(CustomEvent.INIT_CHILD,data));
What I did was add a listener on the parent for changes after the child is added to the stage. Now anytime you want to have children deal with updating themselves, just dispatch the Event.CHANGE from the parent. Bubbling can be true or false.
I would think that if you attach the child;s listener to the Stage (stage.addEventListener...) any object that throws a Event.CHANGE could trigger the child to handle the event.
package
{
import flash.display.*
import flash.events.*
public class Child extends Sprite
{
public function Child():void
{
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true);
}
private function addedToStageHandler(pEvent:Event):void
{
trace("CHILDADDED");
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
this.parent.addEventListener(Event.CHANGE, parent_changeEventHandler, false, 0, true);
}
private function parent_changeEventHandler(pEvent:Event):void
{
trace("PARENT_CHANGED");
}
}
}
IMO, it is almost never appropriate for a child to know or care about its parent. On the other hand, parents nearly always know everything about their children (since they have a direct reference to them). So, in this case, I would simply create a property or method on the child Class that could be set/called by the parent when needed.
This has the advantage of better performance, since creation and handling of an Event is more expensive than simply calling a method or setting a value.
HTH;
Amy
I would listen in each child for
Event.ADDED_TO_STAGE
once it has been added to the stage, you can then reference/listen to the stage for events.
Example
//Child
if(stage) _init(); //Already added
else addEventListener(Event.ADDED_TO_STAGE, _init); //waiting to be added
private function _init(e:Event = null):void
{
stage.addEventListener(CustomEvent.CHANGED, _onStageChanged);
{
I didn't test this, but as long as you dispatch the events from the stage, it should work.
//stage
dispatchEvent(new CustomEvent(CustomEvent.CHANGED));
if you setup your custom event class correctly you can also pass information accross.