2 Replies Latest reply on May 5, 2008 3:19 AM by TristanColgate

    Create display object at runtime


      I have a requirement to create an instance of a DisplayObject whose type will not be know until runtime.

      So, instead of:
      var public myObject:Button = new Button();

      I want to be able to do something like:
      var public myObjectName:String = "Button";
      var public myObject:[myObjectName] = new [myObjectName];

      What is the syntax for doing so?
        • 1. Re: Create display object at runtime
          Gnomann Level 1
          If you only have a name (string) to translate to a class, you'll need the fully qualified (namespaced) name and use the AS introspection flash.utils library; specifically getDefinitionByName().

          var myClassName : String = "mx.controls.DataGrid"; // for instance
          var myClassRef : Object = flash.utils.getDefinitionByName(myClassName);
          var myClass : Class = myClassRef as Class; // should be tested first to make sure is actually a class...
          var myInstance : Object = new myClass(); // with optional params...

          if you're first dealing with general names, like "Button", you'll have to map to the appropriate fullQualName "mx.controls.Button", etc.

          Hope that helps.
          • 2. Re: Create display object at runtime
            TristanColgate Level 1
            Excellent - works like a dream. Thanks for your help.