0

I`m new in flex and could anyone help me?

How do I create a constructor that takes arguments for an MXML component?

zero323
  • 322,348
  • 103
  • 959
  • 935
zgnachvi
  • 33
  • 1
  • 4
  • Possible duplicate of [this post](http://stackoverflow.com/q/8283934/645918) – Art Jun 02 '12 at 14:42
  • 1
    I'm not sure why this was closed; the full question was in the subject line instead of the body text; but that could be easily remedied. – JeffryHouser Jun 05 '12 at 16:30

1 Answers1

2

You can't; MXML Components do not have constructors that you can modify.

You have a few options. The first is to rewrite your component to use ActionScript. This can be tedious in some situations, and trivial in others. It depends what the component does.

A second option os to use public variables on the component. When you create the instance of your MXML Component, set the properties on it. You should be able to access such properties in a preinitialize event handler. prenitinialize will be dispatched after the constructor, but before createChildren().

JeffryHouser
  • 39,401
  • 4
  • 38
  • 59
  • 1
    It's probably better, however, to make use of the life cycle methods (specifically, commitProperties and updateDisplayList) to propagate the changes needed as a result of the variable settings. That way your component can handle it if those properties are changed. – Amy Blankenship Jun 02 '12 at 15:29
  • @AmyBlankenship Making use of the preinitialize event is making use of the Component Lifecycle; albeit not one of the render event methods. The "best" approach depends on what needs to be set and how that affects other things in the component. If a component needs "constructor code" then the preinitialize event is the closest thing you can get in an MXML Component. – JeffryHouser Jun 02 '12 at 15:34
  • 1
    I think that the whole point of Flex is that components ahould always keep themselves in a good state. I think the motivation behind questions like this is a Flash-like mindset, where people throw away an instance and start over if things get too complicated. We usually can'y do that, so people are better off knowing that up front. – Amy Blankenship Jun 02 '12 at 15:59
  • One convention we've adopted at work is to give a component an init() function which returns its parent class instance eg: var comp:MyComponent = new MyComponent().init(args); ...you could achieve the same result with the methods suggested, this just keeps it neater (on the one line) - however, internal references may return null unless the component has been added to the display list, so it's not foolproof, certainly not an alternative to learning about component lifecycle. – MickMalone1983 Feb 26 '13 at 23:25