Event.ADD_TO_STAGE事件

来源:互联网 发布:七喜cms 编辑:程序博客网 时间:2024/04/28 21:36

Display objects often need to perform set-up tasks which depend on the stage. They might wish to access stage.stageWidth or stage.stageHeight, for example. The trouble is, the stage property will return null until that object is on the Display List.

The standard way around this is to put such set-up tasks in an init method, which you then trigger separately:

So the init method is triggered once the object is added to the Display List. This works fine. The only downside is that the object cannot initialise itself. This solution seems slightly clumsy from an OOP point of view also a little verbose. Could the object not auto-trigger its own init method once it is on the Display List?

Not until Flash Player 9.0.28.0, which added support for the ADDED_TO_STAGE event, used as follows:

The trouble is, however, this event erroneously fires not only for the given item, but also when its parents are added to the Display List. This runs your init method multiple times, possibly causing problems.

This issue is Flash Player bug known to Adobe. Read more about the ADDED_TO_STAGE event firing twice issue in the official bug report entry. A workaround with a sample class may be found there. We use that workaround inherited from a superclass for all our display objects, and until the issue is solved we suggest you either use it too, or use the init method solution when set-up code depends upon the stage.

 

 若干评论:

评论1:
It also affects the FlashPlayer on Windows.

An other workaround could be, to remove the listener in the handler.
评论2:
You can remove the listener in the handler, but what if you want the handler to persist for handling repeated add events? If you have code you want to execute when a DisplayObject is added to stage, it would only execute the FIRST time you add it, and never again.
评论3:
The deeper the object is nested, the more times the event will be called. (I attached another example to this issue) Run it and see the event fire twice, uncomment the two lines in Test2.as and see Test3 being instanced twice, and the event will be fired three times on each instance of Test3.


Workaround:

1. Remove the ADDED_TO_STAGE event listener in the ADDED_TO_STAGE event handler.

2. Add a REMOVED_FROM_STAGE event listener on the object.

3. In the REMOVED_FROM_STAGE event handler, add the ADDED_TO_STAGE event again.
评论4:
This should only be an issue if you're adding the child in the ADDED_TO_STAGE handler. If added in the constructor, for example, it should only be called once.
原创粉丝点击