Tuesday, October 4, 2011

Cloning Objects in Flex

So you wanna Clone? I needed a way to clone for any of my VOs without having to go through every VO and adding a clone method and keeping track of my properties and the ObjectUtil don't seem to work that well either so I came up with this quick little recursive method that is still a work in progress but might help you get the same kind of thing accomplished. All this is possible thanks to org.as3commons.reflect so you'll need to go download the swk for this to work. Word File here ObjectUtils


public static function clone(object:Object):*
{
 if (!object)
  return;

 var desc:XML=describeType(object);
 var typeClass:Class=ClassUtils.forName(desc.@name);
 var result:*=ClassUtils.newInstance(typeClass);


 //loop through children and clone child objects recursively
 var x:int=0;
 if (object is ListCollectionView || object is Array)
 {
  for each (var item:Object in object)
  {
   var newItem:Object=clone(item);
   if (object is Array)
   {
    result[x]=newItem;
   }
   else
   {
    result.addItem(newItem);
   }

   x++;
  }
 }
 else
 {
  for each (var a:XML in desc..accessor)
  {
   var currProp:String=a.@name;
   if (a.@access == "readwrite" && currProp != "uid")
   {
    if (ObjectUtil.isSimple(object[currProp]))
    {
     result[currProp]=object[currProp];
    }
    else
    {
     result[currProp]=clone(object[currProp]);
    }
   }
  }
 }

 return result;
}

No comments:

Post a Comment