Optimize a Flex application using deferred instantiations
[转载]http://cookbooks.adobe.com/post_Optimize_a_Flex_application_using_deferred_instant-15826.html
Problem
I have a flex application containing custom components. How can I add them to my Flex Application and make sure it's optimized ?
Solution
We'll use the "deferred instantiation" which mean creating and adding our component's children when we need to (typically when they have to be displayed).
Detailed explanation
My custom component
I have a custom component extending the Container Class. It's really simple as it only displays a picture :
WizardCat
package com.palleas.component
{
import flash.display.DisplayObject;
import mx.core.Container;
import mx.core.UIComponent;
public class WizardCat extends
Container
{
[Embed(source="http://www.cnblogs.com/../assets/wizardcat.png")]
protected var
CatClass:Class;
public function WizardCat()
{
super();
trace("creating wizard cat !");
var
cat:DisplayObject = new CatClass() as DisplayObject;
var
catContainer:UIComponent = new UIComponent();
catContainer.addChild(cat);
addChild(catContainer);
}
}
}
Doing this is really wrong and can be a serious performance issue. Furthermore, components extending the Container class (such as ViewStack, for example) sometimes defers the creation of their children due to the "creationPolicy" property not set to "ALL". This behavior is not here to annoy you but to optimize Flex application loading : instead of automatically draw a component, it will wait until the component is really needed, when it's displayed.
Deferred instantiation
To do the same thing properly, override the "createChildren()" method and create your children there. This way, even if the component is instanciated, it'll wait the application explicitly calls its createChildren() method to create its children (here, it's just a picture) :
package com.palleas.component
{
import flash.display.DisplayObject;
import mx.core.Container;
import mx.core.UIComponent;
public class WizardCat extends
Container
{
[Embed(source="http://www.cnblogs.com/../assets/wizardcat.png")]
protected var
CatClass:Class;
public function WizardCat()
{
super();
}
override protected
function createChildren():void
{
super.createChildren();
trace("creating wizard cat !");
var
cat:DisplayObject = new CatClass() as DisplayObject;
var
catContainer:UIComponent = new UIComponent();
catContainer.addChild(cat);
addChild(catContainer);
}
}
}
As you can see in the picture below, it's still working !
Conclusion
The conclusion of this recipe if quite simple : avoid instanciating and adding children components in constructor. This way, your application should run a little bit smoother!