问题描述
我真的古董为什么会这样。我创建了两个对象。一个是另一个孩子。我注册了两个与事件侦听器ADDED_TO_STAGE。方法onAdded回调函数里的CLASSB执行两次。
I am really curios why is this happening. I created two objects. One is child of another. I registered both with event listener ADDED_TO_STAGE. Method onAdded in classB is executed twice.
这是怎么回事,我该如何prevent这种行为?
Why is this happening and how can i prevent this behaviour ?
感谢名单的答案
public class ClassA extends Sprite
{
public function ClassA ()
{
this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded(e:Event):void
{
trace("ON ADDED 1");
var classB : ClassB = new ClassB();
addChild(classB);
}
}
public class ClassB extends Sprite
{
public function ClassB ()
{
this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded(e:Event):void
{
trace("ON ADDED 2");
}
}
输出:ON ADDED 1ON加入2-ON ADDED 2
OUTPUT: ON ADDED 1ON ADDED 2ON ADDED 2
推荐答案
从<一个href="http://cssmiles.word$p$pss.com/2009/07/25/as3-0-event-added-and-event-added_to_stage/">here:有两个类似的事件:
From here: There are two similar events:
Event.ADDED_TO_STAGE
Event.ADDED
有它们之间的区别:
ADDED
被分派的时候听的DisplayObject添加到另一个DisplayObject(如果不管它是一个舞台对象与否)。此外,如果任何其他的DisplayObject被添加到收听的DisplayObject它被分派
gets dispatched when the listening DisplayObject is added to another DisplayObject (no matter if it is a Stage object or not). Also it gets dispatched if any other DisplayObject is added to the listening DisplayObject.
ADDED_TO_STAGE
在监听的DisplayObject被添加到舞台或向其中添加到舞台的任何其他DisplayObject获取出动。
gets dispatched when the listening DisplayObject is added to the stage OR to any other DisplayObject which is added to stage.
在你的情况下,将分派两次:
In your case it dispatches two times:
1)ClassB的被添加到已经添加到舞台ClassA的。
2)ClassB的被添加到舞台上。
2) ClassB is added to the Stage.
这是有点低级别的API。您可以提供自定义逻辑的情况下.parent是舞台与否。基本上,那些你知道,你并不真的需要倾听这一点,你可以调用:
It's kinda low level API. You can provide custom logic in case of .parent is Stage or not. Basically ones you know that, you don't really need to listen this and you can call:
this.removeEventListener(Event.ADDED_TO_STAGE, onAdded);
要prevent调用两次onAdded回调函数里。
to prevent calling onAdded twice.
另一种方法,它是将CLASSB边建设边CLASSA prevent:
Another way to prevent that is adding classB while constructing classA:
private classB:ClassB = new ClassB();
public function ClassA ()
{
addChild(classB);
this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
这篇关于事件ADDED_TO_STAGE执行多次AS3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!