7

Why doesn't the Flex framework's mxml language support a constructor for components or accept constructor arguments for components? It's as far as I know not possible to declare an ActionScript object in mxml if it takes constructor arguments. I'm curious about the reason. Is it a design choice by Adobe or related to how declarative languages work? For example, why not allow:

<myNameSpace:MyComponent constructor="{argArray}"/> 
Gunnar Karlsson
  • 28,350
  • 10
  • 68
  • 71
  • maybe this will help: http://stackoverflow.com/questions/878043/how-do-i-populate-required-parameters-in-a-custom-mxml-tag – Chris Ghenea Sep 22 '11 at 05:41
  • Thanks Chris for the incredibly fast answer! I was more looking for a reason why it's not possible rather than a workaround - is it something that's generally not possible in declarative languages and why? – Gunnar Karlsson Sep 22 '11 at 06:07
  • And how would you declare more than one argument? Always have them in an array? – J_A_X Sep 22 '11 at 06:21

2 Answers2

6

You can read IMXMLObject help API for more information about your question. They're not telling exactly why an mxml doesn't support constructors, but it says that you must control your mxml component throught its lifecycle events: preinitialize, initialize and creationComplete.

I suppose that's a design decision, considering that an mxml gets translated directly to AS3 code (you can compile your application adding keep-generated-actionscript=true and see what it produces).

Lasneyx
  • 2,110
  • 2
  • 17
  • 21
4

Even if a class is defined in MXML, it is possible to implement a constructor via instantiating an instance variable as follows. This will get called before various events like "preinitialize" or "creationComplete" are dispatched.

<myNameSpace:MyComponent>
  <fx:Script>
  <![CDATA[
     private var ignored:* = myInstanceConstructor();

     private function myInstanceConstructor():* {
         // Do something - called once per instance
         return null;
     }
  ]]>
  </fx:Script>
</myNameSpace:MyComponent>

Moreover, class variables can be initialized in a similar way as follows.

<myNameSpace:MyComponent>
  <fx:Script>
  <![CDATA[
     private static var ignored:* = myClassConstructor();

     private static function myClassConstructor():* {
         // Do something - called once per class
         return null;
     }
  ]]>
  </fx:Script>
</myNameSpace:MyComponent>
CQ Bear
  • 396
  • 2
  • 4
  • Thanks a lot for answer, seems like a very useful approach. Will try it out. – Gunnar Karlsson Oct 02 '13 at 01:09
  • I would change it to `private const __new__():* = construct();` for not only syntactic sugar, but because it should be immutable. I would also make the `construct()*` function `protected` for inheritance. – Mr. Polywhirl Jan 07 '14 at 14:40