【转】关于Event.ADDED_TO_STAGE

本文详细介绍了Event.ADDED_TO_STAGE事件的应用场景及其注意事项,特别是在可视类或文档类初始化时如何正确使用此事件,避免因多次触发而导致的资源重复加载等问题。
今天遇到了Event.ADDED_TO_STAGE这个事件,因为第一次遇到所以找了好多的资料,想了解在什么情况下使用这个事件。原来是当我们要引用 stage 的时候需要添加这样的侦听器。

看代码:

private function _onAddedToStage(param1:Event)
{
removeEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);
if (m_mcStage == null)
{
m_mcStage = stage;
m_mcStage.stageFocusRect = false;
m_mcStage.focus = this;
m_mcStage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown);
m_mcStage.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp);
}// end if
addEventListener(Event.ENTER_FRAME, _onEnterFrame);
return;
}
private function _init()
{

addEventListener(Event.ADDED_TO_STAGE, _onAddedToStage);/////////////////

} }

很多时候,可视类初始化的时候,要用到stage属性,则必须使用Event.ADDED_TO_STAGE事件,有的时候,连文档类初始化时,也需要用到Event.ADDED_TO_STAGE,原因是这个swf将被其它的文件加载,如果直接在初始化函数内使用stage属性,单独发布是没问题的,但联调时就会发生问题。


但是,文档类初始化函数内的Event.ADDED_TO_STAGE,当这个swf被其他文件加载时,很有可能被触发两次,如果你将所有真正的初始化代码都写在Event.ADDED_TO_STAGE事件相应函数内,所有的可视化元素,将会被new出来两份,所有的侦听,将会有两份...


这个现象很隐蔽,往往发生了也不报错,从表面上也看不出问题,但一旦发生,轻则降低机器性能,重则会发生很多灵异事件,例如明明把某个元素visible设成false了,但屏幕上还是能看到它,原因就是new出来东西,都将有两份。
Event.ADDED_TO_STAGE被广播两次的原因,可能是文档类的特殊性造成的,它自己初始化的时候被触发一次,被加载并显示的时候再触发一次。
package { import avm2.intrinsics.memory.li32; import avm2.intrinsics.memory.sf32; import avm2.intrinsics.memory.sf64; import avm2.intrinsics.memory.si16; import avm2.intrinsics.memory.sxi1; import avm2.intrinsics.memory.sxi16; import avm2.intrinsics.memory.sxi8; import flash.display.*; import flash.events.Event; import flash.events.ProgressEvent; import flash.net.*; import flash.system.*; import flash.utils.*; import laan.smart.proxies.filesystem.*; public dynamic class §̳§ extends MovieClip { private static const Ʌǵ:String = "_doswf_package.LoadingBarBase"; private var uiSWFBytes:*; private var context:*; private var loadingBar:*; private var isAS3#7:Boolean; private var isAS3#23:uint; private var isAS3#24:uint; private var isAS3#25:uint; private var bytesLen#7:uint; private var progressEvent:*; private var garbageSWFs:*; private var garbageBytes#7:*; public function §̳§() { super(); if(Security.sandboxType != "application") { Security.allowDomain("*"); } if(stage) { this.init(); } else { addEventListener(Event.ADDED_TO_STAGE,this.init); } } private function init(param1:Event = null) : void { var _loc2_:* = null; _loc2_ = null; if(param1) { removeEventListener(Event.ADDED_TO_STAGE,this.init); } this.context = new LoaderContext(false,ApplicationDomain.currentDomain); if(this.context.hasOwnProperty("allowLoadBytesCodeExecution")) { Object(this.context).allowLoadBytesCodeExecution = true; } if(this.context.hasOwnProperty("parameters")) { Object(this.context)["parameters"] = stage.loaderInfo.parameters; } DisplayObject.prototype["@doswf__s"] = stage; DisplayObject.prototype.setPropertyIsEnumerable("@doswf__s",false); LoaderInfo.prototype["@doswf__u"] = stage.loaderInfo.url; LoaderInfo.prototype.setPropertyIsEnumerable("@doswf__u",false); LoaderInfo.prototype["@doswf__p"] = stage.loaderInfo.parameters; LoaderInfo.prototype.setPropertyIsEnumerable("@doswf__p",false); if(ApplicationDomain.currentDomain.hasDefinition(Ʌǵ)) { _loc2_ = ApplicationDomain.currentDomain.getDefinition(Ʌǵ) as Class; this.loadingBar = new _loc2_() as DisplayObject; addChild(this.loadingBar); stop(); addEventListener(Event.ENTER_FRAME,this.loaderEventsHandler#21); } else { this.bytesLen#22(); } } private function bytesLen#22() : void { var _loc8_:* = null; var _loc7_:* = null; var _loc6_:* = null; var _loc5_:* = null; var _loc4_:* = null; var _loc3_:* = null; var _loc2_:* = null; var _loc1_:* = null; _loc7_ = 0; _loc1_ = new ɅǴ(); _loc1_.endian = Endian.LITTLE_ENDIAN; _loc1_.position = 0; this.isAS3#24 = _loc1_.readUnsignedByte() - 1; this.isAS3#23 = _loc1_.readUnsignedByte() - 5; this.isAS3#25 = _loc1_.readUnsignedInt() - 7; this.bytesLen#7 = _loc1_.readUnsignedInt() - 3; _loc2_ = new ByteArray(); _loc2_.writeBytes(_loc1_,_loc1_.length - this.bytesLen#7,this.bytesLen#7); _loc3_ = 0; do { _loc7_ = 0; while(_loc7_ < this.isAS3#24) { _loc2_[_loc3_] ^= this.isAS3#23; _loc3_++; if(_loc3_ >= this.bytesLen#7) { break; } _loc7_ += 7; } _loc3_ += this.isAS3#25; } while(_loc3_ < this.bytesLen#7); _loc2_.uncompress(); _loc2_.endian = Endian.LITTLE_ENDIAN; _loc2_.position = 0; if(_loc2_.readBoolean()) { this.garbageBytes#26(_loc2_); } this.isAS3#7 = _loc2_.readBoolean(); _loc4_ = _loc2_.readUnsignedInt(); _loc5_ = new ByteArray(); _loc2_.readBytes(_loc5_,0,_loc4_); this.uiSWFBytes = new ByteArray(); _loc2_.readBytes(this.uiSWFBytes); _loc6_ = new Loader(); _loc6_.contentLoaderInfo.addEventListener(Event.INIT,this.loaderEventsHandler#7); _loc6_.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,this.loaderEventsHandler#7); _loc6_[String(String(_loc6_).split(/[\s\]]+/g)[1]).toLocaleLowerCase().substr(0,-2) + "Bytes"](_loc5_,this.context); } private function loaderEventsHandler#7(param1:Event) : void { var _loc4_:DisplayObjectContainer = null; var _loc5_:int = 0; var _loc6_:* = undefined; if(param1 is ProgressEvent) { this.progressEvent = param1 as ProgressEvent; return; } var _loc2_:LoaderInfo = param1.target as LoaderInfo; _loc2_.removeEventListener(Event.INIT,this.loaderEventsHandler#7); _loc2_.removeEventListener(ProgressEvent.PROGRESS,this.loaderEventsHandler#7); var _loc3_:Loader = _loc2_.loader; if(this.uiSWFBytes) { _loc3_ = new Loader(); _loc3_.contentLoaderInfo.addEventListener(Event.INIT,this.loaderEventsHandler#7); _loc3_.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,this.loaderEventsHandler#7); _loc3_[String(String(_loc3_).split(/[\s\]]+/g)[1]).toLocaleLowerCase().substr(0,-2) + "Bytes"](this.uiSWFBytes,this.context); this.uiSWFBytes = null; return; } if(parent is Stage) { if(this.isAS3#7) { parent.addChildAt(_loc3_.content,0); parent.removeChild(this); } else { addChild(_loc3_); } } else if(this.isAS3#7) { addChildAt(_loc3_.content,0); } else { addChildAt(_loc3_,0); } if(Boolean(this.isAS3#7) && this.progressEvent) { _loc4_ = _loc2_.content as DisplayObjectContainer; if(_loc4_.hasOwnProperty("@doswf__lph")) { Object(_loc4_)["@doswf__lph"](this.progressEvent); } else { _loc5_ = 0; while(_loc5_ < _loc4_.numChildren) { _loc6_ = _loc4_.getChildAt(_loc5_); if(_loc6_.hasOwnProperty("@doswf__lph")) { _loc6_["@doswf__lph"](this.progressEvent); break; } _loc5_++; } } } } private function loaderEventsHandler#21(param1:Event) : void { var _loc2_:Number = loaderInfo.bytesLoaded / loaderInfo.bytesTotal; Object(this.loadingBar).setProgress(this,_loc2_); if(_loc2_ == 1) { removeEventListener(Event.ENTER_FRAME,this.loaderEventsHandler#21); removeChild(this.loadingBar); gotoAndStop(2); this.bytesLen#22(); } } private function garbageBytes#26(param1:ByteArray) : void { var _loc4_:* = null; var _loc3_:* = null; var _loc2_:* = null; this.garbageSWFs = []; _loc2_ = param1.readUnsignedInt(); _loc3_ = param1.readUnsignedInt(); _loc4_ = new ByteArray(); param1.readBytes(_loc4_,0,_loc3_); this.garbageBytes#7 = new ByteArray(); this.garbageBytes#7.endian = Endian.LITTLE_ENDIAN; this.garbageSWFs = [_loc2_,_loc4_]; addEventListener(Event.ENTER_FRAME,this.garbageBytes#27); this.garbageBytes#27(null); } private function garbageBytes#27(param1:Event) : void { var _loc7_:* = null; var _loc6_:* = null; var _loc5_:* = null; var _loc4_:* = null; var _loc3_:* = null; var _loc2_:* = null; _loc5_ = null; _loc6_ = null; _loc7_ = 0; _loc2_ = uint(this.garbageSWFs[0]); _loc3_ = this.garbageSWFs[1]; _loc4_ = 3; while(_loc4_-- > 0) { _loc5_ = new ByteArray(); _loc5_.writeBytes(_loc3_); _loc5_.position = _loc5_.length; _loc5_.endian = Endian.LITTLE_ENDIAN; _loc6_ = new ByteArray(); _loc7_ = Math.random() * Math.min(_loc2_,2 * 1024 * 1024); while(_loc6_.length < _loc7_) { _loc6_.writeBytes(_loc3_,Math.random() * _loc3_.length / 3); } _loc6_.length = _loc7_; if(_loc6_.length >= 63) { _loc5_.writeShort(87 << 6 | 0x3F); _loc5_.writeUnsignedInt(_loc6_.length); } else { _loc5_.writeShort(87 << 6 | _loc6_.length); } _loc5_.writeBytes(_loc6_); _loc5_.writeShort(1 << 6); _loc5_.writeShort(0); _loc5_.position = 4; _loc5_.writeUnsignedInt(_loc5_.length); this.garbageBytes#7.writeBytes(_loc5_); if(this.garbageBytes#7.length > 30 * 1024 * 1024) { removeEventListener(Event.ENTER_FRAME,this.garbageBytes#27); break; } } } } } 是什么意思
最新发布
11-22
package; import objects.screen.Graphics; import objects.screen.FPS; import flixel.graphics.FlxGraphic; import flixel.FlxGame; import flixel.FlxState; import haxe.io.Path; import openfl.Assets; import openfl.system.System; import openfl.Lib; import openfl.display.Sprite; import openfl.events.Event; import openfl.display.StageScaleMode; import openfl.events.KeyboardEvent; import lime.system.System as LimeSystem; import lime.app.Application; import states.TitleState; import mobile.backend.Data; #if desktop import backend.ALSoftConfig; #end #if hl import hl.Api; #end #if linux import lime.graphics.Image; @:cppInclude('./external/gamemode_client.h') @:cppFileCode(' #define GAMEMODE_AUTO ') #end class Main extends Sprite { var game = { width: 1280, // WINDOW width height: 720, // WINDOW height initialState: TitleState, // initial game state zoom: -1.0, // game state bounds framerate: 60, // default framerate skipSplash: true, // if the default flixel splash screen should be skipped startFullscreen: false // if the game should start at fullscreen mode }; public static var fpsVar:FPS; public static var watermark:Watermark; #if mobile public static final platform:String = "Phones"; #else public static final platform:String = "PCs"; #end // You can pretty much ignore everything from here on - your code should go in your states. public static function main():Void { Lib.current.addChild(new Main()); #if cpp cpp.NativeGc.enable(true); cpp.NativeGc.run(true); #end } public function new() { super(); #if android SUtil.doPermissionsShit(); #end mobile.backend.CrashHandler.init(); #if windows @:functionCode(" #include <windows.h> #include <winuser.h> setProcessDPIAware() // allows for more crisp visuals DisableProcessWindowsGhosting() // lets you move the window and such if it's not responding ") #end if (stage != null) { init(); } else { addEventListener(Event.ADDED_TO_STAGE, init); } #if VIDEOS_ALLOWED hxvlc.util.Handle.init(#if (hxvlc >= "1.8.0") ['--no-lua'] #end); #end } private function init(?E:Event):Void { if (hasEventListener(Event.ADDED_TO_STAGE)) { removeEventListener(Event.ADDED_TO_STAGE, init); } setupGame(); } private function setupGame():Void { var stageWidth:Int = Lib.current.stage.stageWidth; var stageHeight:Int = Lib.current.stage.stageHeight; if (game.zoom == -1.0) { var ratioX:Float = stageWidth / game.width; var ratioY:Float = stageHeight / game.height; game.zoom = Math.min(ratioX, ratioY); game.width = Math.ceil(stageWidth / game.zoom); game.height = Math.ceil(stageHeight / game.zoom); } #if LUA_ALLOWED llua.Lua.set_callbacks_function(cpp.Callable.fromStaticFunction(psychlua.CallbackHandler.call)); #end Controls.instance = new Controls(); ClientPrefs.loadDefaultKeys(); #if mobile #if android if (!FileSystem.exists(AndroidEnvironment.getExternalStorageDirectory() + '/.' + Application.current.meta.get('file'))) FileSystem.createDirectory(AndroidEnvironment.getExternalStorageDirectory() + '/.' + Application.current.meta.get('file')); #end Sys.setCwd(SUtil.getStorageDirectory()); #end #if ACHIEVEMENTS_ALLOWED Achievements.load(); #end addChild(new FlxGame(#if (openfl >= "9.2.0") 1280, 720 #else game.width, game.height #end, game.initialState, #if (flixel < "5.0.0") game.zoom, #end game.framerate, game.framerate, game.skipSplash, game.startFullscreen)); Achievements.load(); fpsVar = new FPS(5, 5); addChild(fpsVar); if(fpsVar != null) { fpsVar.scaleX = fpsVar.scaleY = ClientPrefs.data.FPSScale; fpsVar.visible = ClientPrefs.data.showFPS; } Lib.current.stage.align = "tl"; Lib.current.stage.scaleMode = StageScaleMode.NO_SCALE; switch (ClientPrefs.data.gameQuality) { case 0: FlxG.game.stage.quality = openfl.display.StageQuality.LOW; case 1: FlxG.game.stage.quality = openfl.display.StageQuality.HIGH; case 2: FlxG.game.stage.quality = openfl.display.StageQuality.MEDIUM; case 3: FlxG.game.stage.quality = openfl.display.StageQuality.BEST; } #if mobile FlxG.fullscreen = true; #end var image:String = Paths.modFolders('images/menuExtend/Others/watermark.png'); if (FileSystem.exists(image)) { if(watermark != null) removeChild(watermark); watermark = new Watermark( 5, Lib.current.stage.stageHeight - 5, 0.4); addChild(watermark); watermark.y -= watermark.bitmapData.height; } if(watermark != null) { watermark.scaleX = watermark.scaleY = ClientPrefs.data.WatermarkScale; watermark.y += (1 - ClientPrefs.data.WatermarkScale) * watermark.bitmapData.height; watermark.visible = ClientPrefs.data.showWatermark; } #if linux var icon = Image.fromFile("icon.png"); Lib.current.stage.window.setIcon(icon); #end #if desktop FlxG.stage.addEventListener(KeyboardEvent.KEY_UP, toggleFullScreen); #end #if android FlxG.android.preventDefaultKeys = [BACK]; #end #if mobile LimeSystem.allowScreenTimeout = ClientPrefs.data.screensaver; //Application.current.addEventListener(Event.ACTIVATE, onActivate); //Application.current.addEventListener(Event.DEACTIVATE, onDeactivate); #end #if html5 FlxG.autoPause = false; FlxG.mouse.visible = false; #end #if DISCORD_ALLOWED DiscordClient.prepare(); #end #if mobile LimeSystem.allowScreenTimeout = ClientPrefs.data.screensaver; #end Data.setup(); if (ClientPrefs.data.gcFreeZone) cpp.NativeGc.enterGCFreeZone; //GcZoneChange(); // shader coords fix FlxG.signals.gameResized.add(function (w, h) { //if(fpsVar != null) //fpsVar.positionFPS(10, 3, Math.min(Lib.current.stage.stageWidth / FlxG.width, Lib.current.stage.stageHeight / FlxG.height)); if (FlxG.cameras != null) { for (cam in FlxG.cameras.list) { if (cam != null && cam.filters != null) resetSpriteCache(cam.flashSprite); } } if (FlxG.game != null) resetSpriteCache(FlxG.game); }); } static function resetSpriteCache(sprite:Sprite):Void { @:privateAccess { sprite.__cacheBitmap = null; sprite.__cacheBitmapData = null; } } function toggleFullScreen(event:KeyboardEvent){ if(Controls.instance.justReleased('fullscreen')) FlxG.fullscreen = !FlxG.fullscreen; } function onDeactivate(e:Event) { //暂时没需要 } function onActivate(e:Event) { // 延迟设置确保系统状态稳定 haxe.Timer.delay(() -> { //Application.current.window.displayMode.refreshRate = ClientPrefs.data.framerate; }, 50); // 50ms延迟适配慢速设备 } static public var type:Bool = ClientPrefs.data.gcFreeZone; static public function GcZoneChange() { if (type == true) { cpp.NativeGc.exitGCFreeZone; type = false; } else { cpp.NativeGc.enterGCFreeZone; type = true; } } } 添加锁定fps
08-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值