Dynamically Instancing Objects ActionScript 3.0 - actionscript-3

I have a variable named "type". And I want to instance an object with the name of the value of type. Here is an example:
var myObjectName = "ball";
var object = new ball(); //Except I want to use the value of myObjectName.
I believe this used to be easy with AS2 when using _global, but I'm not sure how to do it in AS3?
Any help?

First get the class object with flash.utils.getDefinitionByName(), then instantiate that object:
var myClass:Class = getDefinitionByName(myObjectName) as Class;
var object:Object = new myClass();
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#getDefinitionByName()

Related

Serialize class with version?

If I serialize a class in AS3:
var obj:CustomClass = new CustomClass();
var bytes:ByteArray = new ByteArray();
bytes.writeObject(obj);
Lets say I store those bytes in a database and retrieve them at a later date:
var obj:CustomClass = (CustomClass)bytes.readObject();
What if I made a change to that class in that time. That cast would fail. Is there anyway I could differentiate between the 2 ByteArrays and determine that a change to the class has been made?

loading saved bitmap

i had saved a bitmap and i want to load it in runtime.
here is my codes:
var saveDataTxt:SharedObject = SharedObject.getLocal("File");
var textName:String; var textClass:Class;
textName = "Text0" + 1;
textClass = getDefinitionByName(textName) as
Class;
var tx:BitmapData = new textClass(); txtP[1] = new
Bitmap(tx);
saveDataTxt.data.txtArray[1] = txtP[1];
addChild(saveDataTxt.data.txtArray[n]);
but it gives me an error :
**TypeError: Error #1034: Type Coercion failed: cannot convert Object#384c2b1 to flash.display.DisplayObject.**
whats the solution?
To store a bitmap in a shared object, you would need to serialize it to a byte array first (see Is it possible to store images in the SharedObject of Flash?)
What you can do, is just store your custom BitmapData subclass in the shared object (if you don't want to bother with byte arrays)
//you need to register every class/subclass in your shared object
registerClassAlias("flash.display.BitmapData", BitmapData);
var saveDataTxt:SharedObject = SharedObject.getLocal("File");
var textName:String; var textClass:Class;
textName = "Text0" + 1; textClass = getDefinitionByName(textName) as Class;
registerClassAlias(textName,textClass); //need to register the custom class
var tx:BitmapData = new textClass(); txtP[1] = new Bitmap(tx);
saveDataTxt.data.txtArray[1] = tx; //just store the bitmap data
addChild(new Bitmap(saveDataTxt.data.txtArray[n] as BitmapData)); //you have to cast the object as bitmap data

as3 parse a string into URLVariables

for instance if a string is
data = "success=0"
or
data = "success=1&registration=20";
how to parse all variables into URLVariables class object.
var urlVars:URLVariables = new URLVariables(data);
or
urlVars.decode(data);
If i remember right this will solve your problem.
var urlvar:URLVariables = new URLVariables(data);

Actionscript 3 Flex 4.5 Serialization/Deserialization issue?

I'm having a particular issue deserializing an object in a Flex 4.5 Mobile project. I've connected to a Webservice fine and populate a ListBox fine. I can select the item and get the details just fine as well but after serializing the object and trying to deserialize it; the Object definition is getting lost somewhere.
I have a variable for when the user selected the request in a List
private var selectedReq:ServiceRequest;
//Here we instantiate the local variable when user select id in ListBox
selectedReq = event.currentTarget.selectedItem as ServiceRequest;
Each Service Request the user chooses to save will call this method.
private function writeServiceRequest():void {
var filename:String = buildFileName();
var file:File = File.applicationStorageDirectory.resolvePath(filename);
if (file.exists)
file.deleteFile();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
//selectedReq is the private var of the users selected item
fileStream.writeObject(selectedReq);
fileStream.close();
}
When the users want to view the request this method is called.
private function readServiceRequest():ServiceRequest {
var filename:String = buildFileName();
var file:File = File.applicationStorageDirectory.resolvePath(filename);
if (!file.exists) {
return null;
}
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var objReq:ServiceRequest = fileStream.readObject() as ServiceRequest;
fileStream.close();
return objReq;
}
The Class Object is similar to.
public var id:uint;
public var requisitioner:String;
public var requestItems:ArrayCollection //Webservice it's actually List<requestItems>
public var requestProcesses:ArrayCollection // WSDL it's actually List<>
When I try to read/deserialize like
//This line is null but the file exist and the object was written
var objReq:ServiceRequest = readServiceRequest() as ServiceRequest;
if(objReq) {
selectedReq = objReq;
}
If I do not cast the readServiceRequest() as ServiceRequest and simply return an Object; I can iterate through the Object and get the correct values returned from the serialized object.
I can only assume the Classes that Flex created from the Webservice may be causing this? If the values are getting written but not the object type then something has to be lost in the serialization - correct?
Sorry for all the details but I'm a little lost at this time.....any help would be appreciated.
RL
var objReq:ServiceRequest = readServiceRequest() as ServiceRequest;
The above line will continue to return null.
I bet that if you modify it in the following way:
var objReq:ServiceRequest = ServiceRequest(readServiceRequest());
You'll get a run-time exception with a message similar to Can't cast ObjectProxy to ServiceRequest
If that's the case, then the reason you get this is because the AMF serializer doesn't preserve the type information when serializing the ServiceRequest-instance.
In order to fix this you need to call flash.net.registerClassAlias() before the serialization/deserialization.
flash.net.registerClassAlias("fully.qualified.name.ServiceRequest", ServiceRequest);
Try if this work.
Check if event.result is ByteArray.
Read/store the event.result as ByteArray.
var byteArray:ByteArray = event.result as ByteArray;
Get/Deserialize Object using readObject() function.
var object:Object = byteArray.readObject();
Cast to targetted object type. ServiceRequest in your case.
var tartgettedObject:ServiceRequest = object as ServiceRequest;
or
var tartgettedObject:ServiceRequest = ServiceRequest(object);
My bad for not signing in before posting the question.
I did use registerClassAlias which did not help. I did find on the Adobe forum other simular issues and the constant feedback was the problem is most likely caused by the Object Class loosing it's attributes during the file write reason being the Class Objects are written when the Datasource is created from the Webservice. Since my original question we decided to use SQLite which is working perfectly fine - thanks for all you help.
RL

Variable of type asterisk

var test:*;
test = sMC // Some movieClip exported for ActionScript
var f = new test;
Sorry if the question's a bit lame, but I begin to wonder, what does this asterisk, and the snippet mean?
Answering your original question and your question asked in a comment:
An asterisk is a wildcard which means the variable will accept any type of info. Example:
var wildcard:*;
wildcard = "hello";
wildcard = 10;
wildcard = new MovieClip();
All of the above will work.
Variables should be typed as strictly as possible; by this I mean that when you want to assign a MovieClip to a variable, your variable should be typed as a MovieClip. Like so:
var mc:MovieClip = new MovieClip();
This works for anything. If you create your own class, then use that as your type for a variable that holds your class.
var thing:MyClass = new MyClass();
An error will be thrown if you try and assign an unrelated type to a variable, like so:
var thing:MovieClip = "hello";
But as long as your variable type is somewhere along the inheritance chain of what you're assigning to it, then it will work.
var thing:DisplayObject = new MovieClip();
This can be handy if you want to loop through an array containing an assortment of your own classes that extend MovieClip.
var ar:Array = [];
/**
* MyClass extends MovieClip
* MyOtherClass extends MovieClip
*/
ar.push(new MyClass());
ar.push(new MovieClip());
ar.push(new MyOtherClass());
var i:MovieClip;
for each(i in ar)
{
trace(i);
}
Overall the wildcard type is not a recommendation. At worst use Object as everything in flash extends this. One situation where a wildcard or Object can be useful is if you want to create a function that can accept any kind of data. Like so:
var myarray:Array = [];
function addToArray(data:Object):void
{
myarray[myarray.length] = data;
trace(data);
}
OR
function addToArray(data:*):void
{
myarray[myarray.length] = data;
trace(data);
}
Hope this all makes sense.
The asterisk means the variable type is undefined, or a wildcard.
Meaning you can define test as any sort of variable.