Use of Stage Events

**The Problem**
I was recently asked to look at an application problem around stage events. The problem we were seeing is when the application was resized the **removedFromStage** event and the **addedToStage** event were being fired. This was causing unexpected behavior in the application as there was application logic attached to these events.

**The Cause**When the application is started in its default size there are no scrollbars. If the user resizes the application to be smaller then scrollbars are added. If you look in the **Container** class there is a function called **createContentPane()**. This function is called prior to adding the scrollbars. Its responsibility is to create a content pane (a **FlexSprite**). When it creates the content pane it reparents all the children i.e. it adds each child to the content pane and then tells the child that its parent has changed by calling **parentChanged()**. The net result is we see **removedFromStage** and **addedToStage** fired. On subsequent resizing the content pane remains, once it is created it is never removed or recreated.**Workarounds**I found a couple of workarounds. The first is to put a guard condition in your event handlers for the **removedFromStage** event and the **addedToStage** event. The guard condition can check the **creatingContentPane** property on the parent Container.The second workaround is to create the content pane up-front. The **createContentPane()** function is in **mx_internal** namespace so you can override **createChildren()** on the Container and call **createContentPane()**.The downside to creating the content pane up-front is you will increase the memory footprint, the size of this increase will depend on the size of your application.**Recommendations**My recommendation would be to discourage attaching logic to the **removedFromStage** event and the **addedToStage** event. As was shown here they weren’t expected on resize and unexpected behavior was introduced in to the application. There are workarounds but you need to consider how you enforce the workaround within the team. If you can’t enforce them, then don’t do it.**Test Harness**For the purpose of understanding the behavior and testing the workaround I created the following test harness.


2 Responses to Use of Stage Events

  1. Brian Kotek says:

    If you’re building something that runs across both Flex and Flash, there are no other events you can listen for to detect display object creation and destruction. So I would say what really needs to happen is that Flash needs some reliable way to detect and respond to these events.

  2. Pankaj says:

    Thanks Peter.It was a very good insight. My application also relies on these event and I too have seen intermediate ‘addedToStage’ and removedFromStage’ . I think its good idea not to rely on these event.