views:

28

answers:

2

I was wondering what happens to the code contained in an <mx:Script> tag. If I define a function tehre, it just becomes a member function of the generated class. But I noticed that it seems OK for the compiler if I just write some (static) method calls there (specifically, I call Font.registerFont()). It works fine, but I feel kind of guilty for doing this, because I have no idea what's really happening and when the code gets executed.

+3  A: 

MXML is formally an ActionScript generation language. So, the Flex compiler will translate all MXML into ActionScript.

If you wan to see what happens; add the 'keep-generated-actionscript' argument to the compiler and then you can look at the generated ActionSCript code.

http://livedocs.adobe.com/flex/3/html/compilers_14.html#157203

Beyond that; I don't really understand your question. Why would static methods make you feel guilty?

www.Flextras.com
It's not the static methods, it's that I have no idea at what time the code snippets I dump there will execute. Usually, I would place it in some event handler, but I couldn't decide what event would be appropriate.
Hanno Fietz
In that case, you should read up on the Flex Component LifeCycle and make use of those methos/events so that the code executes when you need it to. http://livedocs.adobe.com/flex/3/html/help.html?content=ascomponents_advanced_2.html
www.Flextras.com
@www.Flextras.com - That's also good advice, thanks. Although the specific code I put there is a hack altogether, it doesn't even have to do with the component, I'm just trying to make fonts from an SWC available to the application's CSS. Me thinks the whole thing is some ugly code smell and should be solved in some entirely different way. But that's a different story.
Hanno Fietz
+1  A: 

Following the advice of www.Flextras.com's answer, I kept the generated Actionscript classes and had a look. The code inside <mx:Script> tags is simply put in the class body as-is. Knowing that, I could dig into the Flex livedocs and came across the following paragraph in the section about class definitions:

ActionScript 3.0 allows you to include not only definitions in a class body, but also statements. Statements that are inside a class body, but outside a method definition, are executed exactly once--when the class definition is first encountered and the associated class object is created.

So, putting statements inside a <Script> tag in an MXML file is equivalent to putting code in a static block in a Java class definition.

Hanno Fietz