Switch On The Code RSS Button - Click to Subscribe
Sep
29

Dynamic Classes in Flex and Actionscript

flex icon

I have known about dynamic classes in Flex and Actionscript for a while but I just recently started playing around with them. Basically they are declared classes that can have additional properties tacked on to them at runtime. To add this ability to a class you simply need to add the keyword dynamic to the class definition. So below we have very simple dynamic class.



package
{
  public dynamic class CoolObject
  {
    public var title:String;
    public var count:int;
   
    public function traceMe():void
    {
      var out:String = "";
      out = "title: " + title + "\n";
      out += "count: " + count;
      trace(out);
    }
  }
}

Nothing is different so far except for the dynamic keyword and we can treat the class just like normal - setting properties and calling methods. So something like what's below will work just fine.

var myCoolObject:CoolObject = new CoolObject();
myCoolObject.title = "Mr Cool";
myCoolObject.count = 30;

myCoolObject.traceMe();
// Output:
// title: Mr Cool
// count: 30

However, because it is dynamic, we can also do things like set new properties and add functions. The following code adds a new property and function. It then calls the new function.

myCoolObject.favorite = "The Fattest";
myCoolObject.traceTheCoolest = function ():void
{
  trace(this.favorite + " is the Coolest");         
};

myCoolObject.traceTheCoolest();
// Output:
// The Fattest is the Coolest

We can also loop through all the dynamic properties in the object. Notice from the output that we only get the added properties and functions.

myCoolObject.lamest = "The Reddest";
myCoolObject.old = 50;

for (var i:String in myCoolObject)
{
  trace("Property " + i + ": " + myCoolObject[i]);
}
// Output:
// Property traceTheCoolest: function Function() {}
// Property lamest: The Reddest
// Property old: 50
// Property favorite: The Fattest

Now I am sure there are many more possibilities for uses for dynamic classes. I am interested in hearing the ways that you all have utilized this feature. Also if you have any questions feel free to leave a comment. Until next time, keep coding and commenting.



Posted in Flex, All Tutorials by The Fattest |

One Response

  1. Ariel Sommeria-klein Says:

    This reminds me of Actionscript 2. Unfortunately I’ve never seen any application of this that wasn’t a case of lazy design.
    Ariel

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Powered by WP Hashcash