Friday, April 29, 2011

How to know if an object is dynamic in AS3

In Action Script 3, you can write a class that defines a dynamic object (MovieClip and Object are two examples), this objects can be modified in run-time. What I want to know if is there some way (in run-time, of course) to know if certain object is dynamic or not.

PS: Without making something like this:

function isDynamic(object) {
    try {
        object.newProperty = 'someValue'
    } catch (e) {
        return false
    }
    return true
}
From stackoverflow
  • You can use describeType from flash.utils to describe the object in XML form. Here's the reference to the API: flash.utils.describeType

    function isDynamic(object) {
        var type:XML = describeType(object);
        if(type.isDynamic) return true;
        return false;
    }
    
    unkiwii : "if (type.isDynamic) return true". I think this can be made by just "return type.isDynamic"
  • CookieOfFortune has the right idea, but unfortunately the code itself has problems, isDynamic is an attribute, and the returned value will be a XMLList with a value of a String that reflects a true or false value, not a child node that directly returns a Boolean. It should look more like this:

    function isDynamic(object) : Boolean
    {
        var type:XML = describeType(object);
        return type.@isDynamic.toString() == "true";
    }
    CookieOfFortune : yeah, I was lazy.
    Franky-D : But what if you want to test for dynamic in order to avoid a call to describeType.. sigh.
  • Be careful!

    Anytime you want to use the describeType() function, please please please use the variation:

    import mx.utils.DescribeTypeCache;
    var typeDesc:XML = DescribeTypeCache.describeType(object).typeDescription;
    

    Performance of making repeated calls to the runtime reflective machinery will absolutely suck. That's why Adobe invented the DescribeTypeCache class.

0 comments:

Post a Comment