用callLater解决UI更新问题 UI Updates Lost? callLater to Rescue

Summary

It's very important to know that the Flash runtime does update the UI immediately when you set the properties of a UI component. This behavior may result good performance, but it does create pains for the programmers. In such cases, wrap the property setting statements in a function, add use mx.core.UIComponent.callLater to instruct the virtual machine to call the function after the current UI update has been executed.

Typical Problem

I have this function called refreshUI, which clears all the tabs in a TabNavigator and refills with the updated tabs. After the refilling, I restore the tab selection. However, the problem is that both selectedChild and selectIndex method update the content pane correctly but leave the tab bar out of sync. Finally, I managed to solve it by wrapping the tab selection in a function and register the function to callLater.

Reasoning

With limited knowledge on Flex, i guess TabNavigator was not ready to take the selection property because the UI has not been fully constructed. When the function added through callLater is called, the tab UI has been fully constructed, thus it responds correctly to the selection property setting.

Another method that may help:

public function mx.core.UIComponent.validateNow():void

Validate and update the properties and layout of this object and redraw it, if necessary. Processing properties that require substantial computation are normally not processed until the script finishes executing. For example setting the width property is delayed, because it may require recalculating the widths of the objects children or its parent. Delaying the processing prevents it from being repeated multiple times if the script sets the width property more than once. This method lets you manually override this behavior.