Event.ADD_TO_STAGE事件

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值