I’m taking a break from the pattern tutorials for the moment to write the as3 facebook connect integration library I’ve been meaning to write. With that said, here’s a little method I didn’t realize was around to pull properties from classes. Normally the for..in method you can pull properties available within an object, but this doesn’t work on classes you create.
For instance:
var tempObj:Object = new Object();
tempObj.prop1 = "string1";
tempObj.prop2 = 1234;
tempObj.prop3 = true;
for(var key:String in tempObj)
{
trace(key+' : '+tempObj[key])
}
//traces out the properties in no specific order.
While this works for a normal object here that is dynamic in it’s type, this same thing won’t work for a class you create. Take for instance this class that will be our new value object class.
class TempObjVO
{
public var prop1:String = 'string1';
public var prop2:Number = 1234;
public var prop3:Boolean = true;
}
Now when we try to do the same thing here we get nothing;
var tempObj:TempObjVO = new TempObjVO();
tempObj.prop1 = "string1";
tempObj.prop2 = 1234;
tempObj.prop3 = true;
for(var key:String in tempObj)
{
trace(key+' : '+tempObj[key])
}
//traces nothing out
Luckily we’ve got something up our sleeves to find our properties. It’s called flash.utils.describeType(value:Object) and it returns an XML object.
Now if we use this we can then retrieve xml data of this class. Like so:
var tempObj:TempObjVO = new TempObjVO();
for(var key:String in tempObj)
{
trace('IN THE CLIP CLASS - '+key+' : '+tempObj[key])
}
trace(describeType(tempObj))
//traces out:
//
//
//
//
//
//
As you can see this gives you a ton of information about our class, not just the properties, but what it extends if it’s dynamic, final, or static and the name of the class.
So then with a little bit of code we can pull the class properties and set them to what we want.
For this part we’ll create two of the same value objects, one with the default values and one with our new values. Normally, maybe you would want to pass in a class object to some method that then updates a different class object with values from that object that are also on the new object. Or something to that affect. Anyway, here is our code:
var obj:TempObjVO = new TempObjVO();
obj.prop1 = "different string";
obj.prop2 = 6543;
obj.prop3 = false;
var tempObj:TempObjVO = new TempObjVO();
for each (var variable:XML in describeType(obj).variable)
{
if(tempObj.hasOwnProperty(variable.@name))
{
trace('CHANGING '+variable.@name+'in tempObj from '+tempObj[variable.@name]+' to '+obj[variable.@name])
tempObj[variable.@name] = obj[variable.@name];
}
}
Leave a Reply
You must be logged in to post a comment.