AS3初学者容易迷糊的几个问题

1.Sprite/MovieClip的Enter_Frame事件,不受addChild/removeChild影响

简单点讲:Sprite或MovieClip对象一旦为其添加了Enter_Frame事件监听,对应的Enter_Frame处理函数将会马上被调用,并一直执行下去(不管你是否将其addChild到显示列表,或者将其从显示列表removeChild),直到该对象removeEventListener相应的监听器为止。

同样:MovieClip一旦被new出来,就会自动播放(在未用任何代码stop()的前提下),不管你是否将其addChild或removeChild

注:其它事件也类似,在AS3的世界中,事件一旦被监听,要想停止事件响应,唯一的方法只能是removeEventListener。(这一点跟c#中完全不同,在c#中不管是webform还是winform,一旦按钮被disabled了,肯定就无法触发按钮的Click事件,但在AS3中,组件是否被禁用,跟组件是否能响应事件完全是没有任何关联的!)

测试代码:

var _sprite:Sprite = new Sprite();
_sprite.graphics.lineStyle(1,0);
_sprite.graphics.beginFill(0xff0000);
_sprite.graphics.drawCircle(0,0,50);
_sprite.graphics.endFill();

_sprite.addEventListener(Event.ENTER_FRAME,onSpriteEnterFrame);//实际上:程序执行到这里就会一直不停的跑onSpriteEnterFrame了

function onSpriteEnterFrame(e:Event):void{
	trace("我是_Sprite",getTimer());
}

addChild(_sprite);
_sprite.x = stage.stageWidth/2 ;
_sprite.y = stage.stageHeight/2 ;

_sprite.addEventListener(MouseEvent.CLICK,onSpriteMouseClick);

function onSpriteMouseClick(e:MouseEvent):void{
	removeChild(_sprite);//移除自己	
	_sprite=null;//注意:即使把自身设置为null,原来注册的onSpriteEnterFrame函数仍会一直执行,正确的方法只能用removeEventListener才能移除Enter_Frame事件
	//_sprite.removeEventListener(Event.ENTER_FRAME,onSpriteEnterFrame);
}

2.ADDED、ADDED_TO_STAGE、REMOVED、REMOVED_FROM_STAGE这几个事件的区别

var _container:Sprite = new Sprite();

_container.addEventListener(Event.ADDED,onAdded);
_container.addEventListener(Event.ADDED_TO_STAGE,onAddedToStage);
_container.addEventListener(Event.REMOVED,onRemoved);
_container.addEventListener(Event.REMOVED_FROM_STAGE,onRemovedFromStage);

function onAdded(e:Event):void {
	trace("onAdded:",e);
}

function onAddedToStage(e:Event):void {
	trace("onAddedToStage:",e);
}

function onRemoved(e:Event):void {
	trace("onRemoved:",e);
}

function onRemovedFromStage(e:Event):void {
	trace("onRemovedFromStage:",e);
}

addChild(_container);
//onAdded: [Event type="added" bubbles=true cancelable=false eventPhase=2]
//onAddedToStage: [Event type="addedToStage" bubbles=false cancelable=false eventPhase=2]

var _sub:Sprite = new Sprite();

_container.addChild(_sub);
//onAdded: [Event type="added" bubbles=true cancelable=false eventPhase=3]

/*_container.removeChild(_sub);
//onRemoved: [Event type="removed" bubbles=true cancelable=false eventPhase=3]*/

removeChild(_container);
//onRemoved: [Event type="removed" bubbles=true cancelable=false eventPhase=2]
//onRemovedFromStage: [Event type="removedFromStage" bubbles=false cancelable=false eventPhase=2]

_container.removeChild(_sub);
//onRemoved: [Event type="removed" bubbles=true cancelable=false eventPhase=3]

区别:

ADDED是子对象被添加到自身时触发,ADDED_TO_STAGE是对象本身被添加到显示列表时触发;类似的:REMOVED当子对象从自身移除时触发,REMOVED_FROM_STAGE是自身从显示列表中移除时触发;

ADDED/REMOVED事件会冒泡,而ADDED_TO_STAGE/REMOVED_FROM_STAGE不冒泡,也就是说每次addChild或removeChild自身时,下面的ADDED/REMOVED事件也会冒泡上来先被触发,然后才触发ADDED_TO_STAGE/REMOVED_FROM_STAGE事件.

你可能感兴趣的:(as3)