2 Replies Latest reply on Jul 24, 2007 11:38 AM by toddmz2

    Is it possible to use 'this[ ]' when declaring component  type/class?

      I'm trying to make my program more dynamic by not having to setup each newly added component. Right now, I'm creating these components using a switch statement that gets it's data from XML:

      switch( itemDetails.type )
      case "U_Flex_SlideCanvas":
      comp = new U_Flex_SlideCanvas( itemDetails.key );
      return comp;
      case "U_Flex_Button":
      comp = new U_Flex_Button( itemDetails.key );
      return comp;

      What I'd like to do is this to simplify the code, but I don't know if it's even possible with actionscript:

      comp = new this[ itemDetails.type ]( itemDetails.key );

      I'm struggling to even find the correct terminology to explain this problem. So if nothing else, if anyone has any keywords that might help me in my google searches, that'd be great too. Thanks.
        • 1. Re: Is it possible to use 'this[ ]' when declaring component  type/class?
          I am not certain that this will help you ... it is based upon the description for the "Class" class in the Action Script Language Reference. I don't really see a way to achieve what you want to do without some form of manual initialization, because AS does not appear to have the equivalent of the Java reflection mechanism. However, with some fairly simple initialization I think you can at least simplify your situation from a "switch" statement to the simple initialization.

          The following illustrates the basic concept of my attempt:

          var m: Object = new Object;
          m["String2"] = String;
          var c: Class = m["String2"];
          var s: String = new c("ok");

          This creates a String from a Class variable. I see this being used in the following manner in your case:

          Put the following lines into the initialization for your class (except that the declaration of the "controlClasses" variable would actually be at the top of the class, making it a class variable, possibly static):

          private var controlClasses: Object = new Object();

          controlClasses["U_Flex_SlideCanvas"] = U_Flex_SlideCanvas;
          controlClasses["U_Flex_Button"] = U_Flex_Button;

          You can then use the following statement to obtain the control instance for the requested type:

          comp = controlClasses[itemDetails.type](itemDetails.key);

          I haven't tried this, and so I am not certain that it will work! And there may be a simpler approach (one that does not require the initialization step).
          • 2. Re: Is it possible to use 'this[ ]' when declaring component  type/class?
            toddmz2 Level 1
            That looks like a great work-around. I'll give it a try. Thanks a million!