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.
若干评论:
An other workaround could be, to remove the listener in the handler.
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.