Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone an object in Flex?

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] ...
like image 362
coulix Avatar asked Feb 19 '09 16:02

coulix


2 Answers

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()...

like image 147
LiraNuna Avatar answered Oct 23 '22 14:10

LiraNuna


ObjectUtil

The static method ObjectUtil.copy() is AS3's "Object.clone()":

public static function copy(value:Object):Object

Copies the specified Object and returns a reference to the copy. The copy is made using a native serialization technique. This means that custom serialization will be respected during the copy.

This method is designed for copying data objects, such as elements of a collection. It is not intended for copying a UIComponent object, such as a TextInput control. If you want to create copies of specific UIComponent objects, you can create a subclass of the component and implement a clone() method, or other method to perform the copy.

like image 34
Fernando Briano Avatar answered Oct 23 '22 15:10

Fernando Briano