Alex Rivera | Logout

How to clone an object in Flex?

Asked 2009-02-19T16:20:47.540
9

I want to clone a Canvas object, which contains a Degrafa Surface with several Geometry shapes.

I tried the naive approach:

return ObjectUtil.copy(graph_area) as Canvas;

which resulted in errors:

TypeError: Error #1034: Type Coercion failed: cannot convert Object@63b1b51 to com.degrafa.geometry.Geometry.
TypeError: Error #1034: Type Coercion failed: cannot convert Object@63b1039 to com.degrafa.geometry.Geometry.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at mx.core::Container/addChildAt()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\Container.as:2196]
    at mx.core::Container/addChild()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\Container.as:2140] ...
Edit
Report

1 Answer

9

What you want is called a deep copy, generate a new instance with the same information of the original.

The only way I know how to do it is using ByteArray as follows:

private function clone(source:Object):*
{
    var buffer:ByteArray = new ByteArray();
    buffer.writeObject(source);
    buffer.position = 0;
    return buffer.readObject();
}

AS3 is really lacking Object.clone()...

answered 2009-02-20T09:59:13.393

Your Answer