All of “actionScript”
Jackson Dunstan shows how to squeeze more speed out of your functions.
ActionScript Tip: Stage access
I often need access to the stage, primarily to listen for MouseEvents. However, if you have a custom class that extends DisplayObject (or Sprite or MovieClip) and you try and add listeners to the stage object in its constructor function, this will fail as its 'stage' property will be null. This makes sense as the constructor function is called before a DisplayObject is added to the display list.
Say we want to create a new Doohickey object:
var myDoohickey : Doohickey = new Doohickey(); addChild(myDoohickey);
public class Doohickey extends Sprite { public function Doohickey() { initialize(); } private function initialize():void{ trace("Stage: " + this.stage); }
}
This will trace out "Stage: null", as initalize() is called before its parent calls addChild(myDoohickey).
One solution is to take the initialize function out of the constructor function, and make it a public function the parent class has to call:
var myDoohickey : Doohickey = new Doohickey(); addChild(myDoohickey); myDoohickey.initialize();
The solution I prefer, however, uses the ADDED_TO_STAGE event:
public class Doohickey extends Sprite {
public function Doohickey() {
this.addEventListener(Event.ADDED_TO_STAGE, initialize);
}
private function initialize(e:Event = null):void{
this.removeEventListener(Event.ADDED_TO_STAGE, initialize);
trace("Stage: " + this.stage);
}
}
