您可以創建,你會分配階段參考一個公共的靜態屬性的類,從而使舞臺訪問整個應用程序如以下:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
GlobalVars.stage = stage;
var keyboardVelocity:KeyboardVelocity = new KeyboardVelocity();
}// end function
}// end class
}// end package
import flash.display.Stage;
internal class GlobalVars
{
public static var stage:Stage;
}// end class
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;
internal class KeyboardVelocity extends EventDispatcher
{
public function KeyboardVelocity()
{
var stage:Stage = GlobalVars.stage;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStageKeyDown);
}// end function
private function onStageKeyDown(e:KeyboardEvent):void
{
trace("key down");
}// end function
}// end class
注:我用內部類以便您可以簡單地將代碼複製並粘貼到文檔類中並運行它。理想情況下,你會將這些類分離到他們自己的文件中。
就我個人而言,我並不喜歡讓對象在全球範圍內訪問,因爲它構成潛在的安全風險,在我看來是不好的做法。您應該考慮只需在下面的解析階段的引用您的KeyboardVelocity
類,如:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var keyboardVelocity:KeyboardVelocity = new KeyboardVelocity(stage);
}// end function
}// end class
}// end package
import flash.display.Stage;
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;
internal class KeyboardVelocity extends EventDispatcher
{
public function KeyboardVelocity(stage:Stage)
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStageKeyDown);
}// end function
private function onStageKeyDown(e:KeyboardEvent):void
{
trace("key down");
}// end function
}// end class
@Tuarayi - 我同意你關於全局靜態變量,那麼一般。它確實打敗了面向對象模式的目的。這就是說 - 在構造函數中傳遞變量的引用也變得非常粘稠,並且促進了緊密耦合。實際上我並沒有想到在這一點上有一個「正確」的答案,除了「除非真的需要使用全局變量」外,舞臺也是我發現自己經常參考的一個,所以這是一個很好的候選人。 @OP這兩種策略都有效,都有潛在的問題。 – Bosworth99 2011-05-24 22:24:12