Copy Flex UIComponent
I was trying to copy a canvas(UIComponent), but realize that it’s not a simple job as it looks like.
1. One can use the ObjectUtil.copy()..method to copy a simple object, but we can not use the same for UIComponent.
2. Secondly, one can use Bitmap to copy the Image type. Like…
public static function cloneImage(image:Image):Image
{
var clone:BitmapData = Bitmap(image.source).bitmapData.clone();
var bitmap:Bitmap = new Bitmap(clone);
var newImage:Image = new Image();
newImage.source = bitmap;
return newImage;
}
3.Thirdly, we can use the componentDescriptor to create a container
Like..
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”horizontal”>
<mx:Script>
<![CDATA[
private function cloneButton_clickHandler (event:MouseEvent):void
{
var childDescriptors:Array = original.childDescriptors;
var descriptorsCount:int = childDescriptors.length;
for (var i:int; i < descriptorsCount; i++)
{
cloned.createComponentFromDescriptor(original.childDescriptors[i],
false);
}
cloned.validateNow();
}
]]>
</mx:Script>
<mx:Button label=”Clone Canvas” click=”cloneButton_clickHandler(event);” />
<mx:Canvas id=”original” width=”100″ height=”100″ borderStyle=”solid” >
<mx:Label text=”Some Label” />
<mx:ComboBox dataProvider=”{['data1', 'data2']}” bottom=”0″ />
</mx:Canvas>
<mx:Canvas id=”cloned” width=”100″ height=”100″ borderStyle=”solid” >
</mx:Canvas>
</mx:Application>
but, still there is a problem in the above method. It copy only the first level children.
For more usefulness we need to make RECURSIVE call to this method to copy each and every children it has which is really frustating…:(
4. I also tried to implement this by using Reflection API or taking a snapshot of the current view…
But, unfortunately flex does not have snapshot method. I guess we need to take help of ExternalInterface to implement the sanpshot method..
After going through all this I find that flex should have make this more simplify by providing an interface to clone any UICompoent.
Sorry to say, I guess flex is really lagging in this regard…