Thursday, March 10, 2011

Copying Related Properties into Objects

Lets say that you have a hierarchy of VO's that share some properties....
for example:
  • OrderedItemVO extends ProductItemVO
  • PriceExtendedVO extends PriceVO
and the issue is that you did a search (or whatever) and you have a collection of products, that you then want to add to an order (in which they need to be upgraded to an ordered item vo).

The brute force solution would be to create a new OrderedItemVo() and copy a property one by one into it like:
var copy: OrderedItemVO = new OrderedItemVO(); =
copy.description = source.description

but here is an alternative method that will do this a little more elegantly:

public static function copy(source:Object, destination:Object):void // NO PMD
   // First grab all of our writeable getter/setters and variables
   var info:XML =  describeType(source);
   var setters:XMLList = info..accessor.(@access == "readwrite");
   var vars:XMLList = info..variable;
   var merge:XMLList = setters + vars;
   //loop over everything adding the properties
   var prop:String;
   var type:String;
   var isDynamic:Boolean = info.@isDynamic == "true"
   for each (var propXml:XML in merge)
    prop = propXml.@name;
    //skip over uid... a good idea to exclude this one.
    if (prop == "uid")
    if (destination.hasOwnProperty(prop) || isDynamic )
     destination[prop] = source[prop]

1 comment:

  1. This comment has been removed by a blog administrator.