7

I've implemented a MXML custom components and I would like to pass parameters to the constructor:

 newUser = new userComp("name");

instead of using set methods.

Is this possible if the custom components has been built in MXML (with initialize=myPseudoCostructor() method ?)

Or I can only set the parameter with an additional line of code?

phwd
  • 19,975
  • 5
  • 50
  • 78
aneuryzm
  • 63,052
  • 100
  • 273
  • 488

3 Answers3

5

You can't pass variables into an MXML component's constructor. I don't even believe it's possible to define a constructor in an MXML component, though I could be wrong. You can, however, setup properties which have default values, and are changed post-construction.

You could also create an initialization function which is also invoked post-construction.

bedwyr
  • 5,774
  • 4
  • 31
  • 49
  • ok, so if I create a custom component with mxml I can only set the variables later invoking its methods. – aneuryzm Apr 19 '10 at 06:15
  • You can define a constructor in/of an MXML component, and you can even have parameters in that constructor; but the restriction is that all parameters to the constructor must be optional. – Panzercrisis Jun 24 '13 at 13:44
  • I'm getting `Multiple constructor definitions found. Constructor may not be defined in code.` It says [here](http://livedocs.adobe.com/flex/3/html/help.html?content=basic_as_2.html) (in a note) that this is explicitly disallowed. – dm78 Dec 05 '13 at 05:29
3

I've recently run into this problem - what you can do is create an initialisation function which returns the component:

Inside the component (called, for argument's sake, MyComponent):

public function init(...args):MyComponent {

    //Add constructor code here

    return this;    
}

...when creating a component, you can invoke like this:

var myComp:MyComponent = new MyComponent().init(args);

As it returns the object, you can treat it as a constructor. I've had to use this method a lot lately, seems the best method for getting round the problem.

MickMalone1983
  • 1,054
  • 8
  • 17
1
IN COMPONENT (cosa)

<fx:Declarations>
 <fx:String id="name">Jon Doe</String>
</fx:Declarations>
<fx:Script>
 trace("hola "+name)
</fx:Script>
<s:Label text="Hola {name}"/>

IMPLEMENT
<cosa name="Juan Perez"/>
Zorel
  • 11
  • 1