Is there a benefit to embedding ActionScript in MXML when developing Flex apps? - apache-flex

I always thought that separating the UI from the logic is the way to go like the use of class files in Flash CS3/CS4 or MVC in web frameworks but recently there are plenty of examples and posts using ActionScript embedded in MXML.
Is there a benefit to doing this? Am I missing something.

Don't get too caught up on the "rules" of MVC and the like. Ultimately you want your code to be setup in such a way that it will minimize the impact/churn of future changes. It's less important "where" the code is and more important what and how it's interacting with other code. I see far to many people take a simple component like a login screen and make models, view, controllers, view helpers, service facades, etc. It ends up being like 75+ lines of code for something that should have been about 20. It also spreads the code amoungst a bunch of files rather than one. So in the end, you've made maintenace hard, not easy. I'm not arguing for ignoring design patterns, but rather being practical about it. Hope this helps.

In my experience, there's not much of a difference whether you write a component in ActionScript + MXML, or solely in Actionscript. Personally, if I'm writing something that's layout heavy with a little logic, I'll do it in MXML. Conversely, if it's code heavy and has little layout, I'll write it in Actionscript.
I suppose you could always separate the view and model, but then you have more files to maintain. Sometimes it makes sense, but I have yet to see a compelling reason to do it all the time.

I go by a few simple rules:
If a bit of code is just a single short line and it isn't something you can reuse elsewhere -- mere glue code -- put it directly in the MXML tag.
If it's too long to fit comfortably in the MXML tag or it is something multiple components in that MXML file can use, put it in a function in a Script tag within the same file, and call the function from the MXML tag(s).
Everything else -- full classes, large functions, things used by multiple MXML files -- goes in a separate .as file. This includes single-LOC methods that are part of a larger class, as opposed to the standalone functions the other rules cover.

I agree with Erich Douglass, to a point. Generally, if I can do the layout with MXML it's just easier to maintain. I mean, who wants to write all that crap in a createChildren override if you don't have to? Besides, the MXML is easier to read.
Whatever you do, though, remember that if you are merely calling a separate script file for an MXML component (Foo.mxml calls Foo.as for its ActionScript) you are losing the code highlighting feature that helps you work between the MXML and the ActionScript. I like to keep them both in the same place, so when I click on an ID in an MXML element I can see at a glance where it's being referenced in the AS.

Related

What's better for view as or mxml on mobile

As the title says what's better for writing views on mobile application : AS or MXML, in performance and visual?
I've tested the two ways and I found out that sometimes the mxml works better than AS
I disagree with #Apocalyptic0n3: HTML and JS are 2 completely different languages, whereas MXML is just a declarative way to write AS. MXML code is compiled to AS first and the generated AS is then compiled to ABC bytecode, just like regular AS.
This means that as long as you use the Flex component hierarchy for writing your components in AS there will be hardly any performance difference. And anything you can write in MXML can be written in AS. Some of the generated code may be useless to your specific use case, so there's some optimization that could be done there, but it would hardly be noteicable in most cases. (If you write pure AS components outside the Flex framework, that's a whole other story of course)
The main difference is the speed at which you write your code, because you're going to put a lot more time into writing a component in AS as opposed to MXML.
In MXML you would also naturally use data bindings, whereas in a component written in AS you would usually set properties by overriding the commitProperties() method. There is a significant performance difference to be made here, but it doesn't mean you can't use bindings in AS, or you can't override commitProperties in an MXML-based component.
MXML is far superior than AS3 in terms of GUI layouts. It's faster to write and far, far more flexible (and you can still use AS3 to boot), and generally faster in overall speed, especially since you do not need to bind resize listeners. MXML and AS3 are meant to be used together, just as HTML and JS are.

Flex <fx:Script /> best practices?

Just wanted to ask about what to do when using as includes (ie <fx:Script source="includes/my_as3_file.as" />.
The problem is that in all of my files I'm using class-only modifiers, such as private, public protected, and FB sometimes protests regarding these. A friend told me that what he does is changing the file extension to .ias, but in this way, he loses code highlighting, content-assist and enabling breakpoints.
Thanks.
I like to use something called a ViewHelper (posted a link)
http://www.kensodev.com/2010/08/19/keep-your-mxml-files-neat-with-view-helpers/
This way, the MXML file is pure MXML at all times, and the view helper is coupled and has a reference to the view meaning you can do something like this in your view helper
myView.dataGrid.visible = false;
And of course many more things.
Even when I use RobotLegs's mediators, I still use the view helper for all actions that concern the view such as animations, hiding and shoeing things, state changing and more. I use the mediators only to mediate with the RobotLegs framework (re-dispatch events) and listen to the eventDispatcher.
Personally, I'm not a fan of using includes. As you've mentioned, it tends to obfuscate what's actually going on within a view, and makes it difficult to quickly scan a file and grok it's behaviour.
One of the best practices I've always followed is to reduce the amount of code within an <fx: Script /> block to almost none.
If you are using an include file, this suggests that your views are very script-heavy, which can lead to poor code reuse, and difficulty in writing testable code.
Instead, consider using the Presentation Model pattern where the logic is moved out to a separate class. Alternatively, there's also the Mediator pattern, however personally I've found this leads to more heavily coupled code - though that's likely down to my crappy execution, than a failing of the pattern.
Use code behind!
or
[mxml_file]AS.as for Actionscript file name.
ex MXML: MyView.mxml and the as file MyViewAS.as
then it will look like <fx:Script source="MyViewAS.as" />
Renaming the .as file to .ias, in my opinion, is one of the worst solutions one can come up with ( it's just horrible ). I also kinda disagree with Marty, because in Flex 4, the architecture is different from Flex 3 ( although Spark is built on top of MX - if we were talking about Flex 3, then I'd agree with what Marty said ). In Flex 4, the Skin is now considered to be the "View" and class making use of the view is the "Controller"... meaning that things are now much better separated than they were in Flex 3, where a components kinda played the role of both the View and Controller ( http://www.slideshare.net/saurabhnarula/flex-4-skinning-2634949 ).
Coming back to the original problem: It's true that Flash Builder is not perfect, but if you know that you don't have any errors in your code and it keeps on throwing some weird stuff at you, then simply try closing it and starting it again ( Clean your project afterward ). Whenever I set an .as file as the source for my MXML component, I like to have the file next to the MXML class ( ex: MyMXMLComponent.mxml and MyMXMLComponentAS.as, both being at the same level - source="MyMXMLComponentAS.AS" ). This 99% of the time works fine, but really rarely, I might have also received some weird errors from Flash Builder ( which usually got solved by closing it and cleaning the project afterward - on a couple of occasions, there was actually an error in my code which seemed to totally confuse/crash the compiler and make it throw some really senseless error messages, so definitely try to make sure that your code is correct ).
Personally, I'd suggest that instead of using .as files, you try to use the "code behind" approach ( search on Google / Adobe for more info on this - I wanted to post a link, but since I'm a new user, I'm limited to 1 link / post... hah ). Using code behind, you will surely never run into the problems you might run into with .as file and you will surely never have problems with code hinting. In case you have never used code behind before, then it might feel "strange" at the beginning, but you'll get used to it and you'll surely not want to write code "the old way" ever again.

what are the advantages of using mxml over actionscript in a flex application?

they both seem to accomplish the same things with different syntax, whats the point of using two different technologies. Please highlight every possible benefit of using mxml. Also are there scenarios when one is more beneficial than the other and why.
Please clarify this runtime behavior of mxml vs AS3 as discussed in Oreilly Flex 4 Cookbook page 1:
" Many newcomers to Flex wonder how MXML and ActionScript relate to one another.
The MXML compiler (mxmlc), after parsing through the different idioms, translates
them into the same objects, so that this:
<s:Button id="btn" label="My Button" height="100"/>
and this:
var btn:Button = new Button();
btn.label = "My Button";
btn.height = 100;
produce the same object. The major difference is that while creating that object in
ActionScript (the second example) creates the button and nothing else, creating the
object in MXML adds the button to whatever component contains the MXML code.
The Flex Framework handles calling the constructor of the object described in MXML
and either adding it to the parent or setting it as a property of the parent. "
Usually,
MXML is used to build the user interface
ActionScript is used to code the logic of your application
Of course, you can also build the user interface with ActionScript but :
it will take you more time
MXML views are easier to read than AS views
In terms of user interface, ActionScript should be used only to manage view elements (add, remove, ...) at runtime.
Edit
Within a Flex application, one is expected to favor using mxml over AS, provided both uses are available. In case mxml doesn't provide a solution , the user can fallback to AS3. Flex is a framework, therefore you would expect that the emphasis is put towards mxml, rather than AS3. Like most frameworks , the idea is to hide the details in order to facilitate design and supposedly make programming more accessible.
Everything comes at a cost though, you can't really expect mxml to be faster than AS3 since it's built on top of it. A logical conclusion would be to decide on a case basis. What are your app requirements, is there really a performance gain in using this component or not etc... Apart from the fact that Flex as a whole is bound to be slower than AS3, I don't think you can set general rules. One could add that if one is worried about performance, why choose Flex in the first place...
End of Edit
The Flex framework is geared towards building RIAs, therefore it comes with a bunch of components to that effect and mxml which mainly deals with the layout of these components, Actionscript being the language the Flex framework is built upon, will typically be used for the logic of your application.
The question is not really why choose one over the other. It's the same approach you would have if you decide to develop using a language directly or using a framework based on this language. It's like comparing JQuery & Javascript or CodeIgniter & PHP .I don't mean to imply that the reasons to use JQuery are the same regarding using Flex. Whilst JQuery will attempt to hide browser specificities and make JS more accessible , Flex's purpose is entirely different.
If you're developing RIAs, Flex makes sense, if you're developing games, not really. All you can do with Flex can be done with AS3 , only you wouldn't want to spend time developing DataGrids or HBoxes whilst you could spend more time on your app structure & design.
On the other hand, if you're developing a website or a game , you wouldn't want to add the weight of the Flex framework to your swf, simply because you've added a few Image components and a couple of Labels.
Flex is not adapted to every situation, unlike my previous Javascript or Php examples , Flex's purpose is not to make the language it's based upon more accessible or easier to deal with. Flex has a very specific target.
A similar question might be "what is the advantage of using HTML over Javascript for the UI?"
I suppose you are really asking "what is the advantage of using a declarative UI over an imperative one?"
Declarative UIs are more like configuration -- no logic (or in the case of MXML, very little logic). Declarative UIs separate the specification of the view from the behavior and data.
Tooling almost always prefers declarative UIs as well, because declarative specs tend to be extremely well suited to serialization... much easier for a tool to update MXML than ActionScript with properties and such.
As you get more familiar with the concept, declarative UIs start to feel more natural, and most people tend to prefer them.
Productivity, you create view elements with MXML faster than with AS3.
Under the surface MXML get's converted to the same AS3 bytecode as if you'd write in plain AS3 so the question if MXML makes the app slower comes down to how well the Flex compiler does the conversion.
As for the original question I would say that MXML is for visual development but as said before you hit the limits when trying to create custom components.
Personally I write Flex apps in 99.9% plain AS3 because I can't stand MXML. The only MXML file is the required Entry class so the compiler knows it should be a Flex app that it compiles.
Either way your app is going to get converted to an ActionScript object.
The advantage of using MXML is user friendly and more control on the look and feel of application. sometimes its easy to fix issues aligining your components on the right pane or panel with MXML.
The advantage i see using actionScript is command over your application, you have more control. Sometimes your MXML does not get you the itch of what you are looking and actionScript gives you more power.
I would suggest you to play with both to build an application which can give you less headache and better results.
None, Flex is for learning, as you learn more you use more .as and then one day... you use 0 Flex.
For one it's slow.
(edit - answer to comments)
'Why is flex slow' - it creates computer generated .as code. Equivalent functionality in .as is faster and smaller.
'MXML separates UI from code' - I'd say no it does not. First of ... it's XML.
If you are new, check out other frameworks, like Away3d, FDT and MinimalComponents. As you get more advanced, you use less MXML and one day no MXML, you are writing pure .as.
Anything in Flex can be done in HTML5/.js better. Also .as is much better than HTML5/.j
It's like a learning tricycle, and good for corporate developers that do drag and drop, they think of themselves as programmers. Software engineers... don't stay with Flex for long before evolving.
Here: http://www.youtube.com/watch?v=TL2t8eOs1XE
I feel sorry for you if you stay in Flex and don't advance.

flex newbie: can MXML be generated on the fly

Flex newbie question: can MXML be generated on the fly, like HTML is generated by a server?
If yes, is it ok to do so or am I missing an important Flex architectural principle.
Sort of... but it still needs to be compiled. MXML is not rendered directly, it is first compiled into ActionScript 3.0, and then into a typical SWF... so, you cannot serve your users with MXML. However, like almost all programmming languages, you can use automatic code generation to ease development tasks.
There is IIS/Apache component given by adobe that can generate your mxml -> html+swf using on the fly compilation, and it also caches the last compiled file.
However its not recommended for bigger projects as it has certain problems that you cant make libraries of your code and organize code accordingly. Namespace usage is very limited.
MXML is just a way of describing user interface layout and scripts. This information is then "compiled" into ActionScript, then converted to SWF format for use in the Flash player.
So, yes, you can generate MXML on the fly, in that you can create a text file that contains valid MXML syntax, then use mxmlc to compile it, but there's no way (that I'm aware of) to create MXML and "add" it to your current movie such that the information appears as it would were it compiled.
It is not officially supported but there is a few similar projects doing stuff similar to this.
as3Query let you create things with xml.
Using createComponentFromDescriptor() maybe can get what you want.
Should be more as I remember, but can't find it out at this moment... Searching for "MXML runtime dynamic compilation" or something like that should be helpful...

Is it a bad idea to get rid of the mx: in your Flex code?

I am a newbie at Flex, and I don't like the way you have to write the namespace mx: for every control declaration you write. It makes the code cluttery. I would like to write:
<Panel ...
rather than
<mx:Panel ...
I tried writing
xmlns="http://www.adobe.com/2006/mxml"
for the top level element instead of
xmlns:mx="http://www.adobe.com/2006/mxml"
In the top level declaration. This work to an extent, but broke some existing code. For one, XML data that are defined in the document are all appended with aaa: as the namespace during runtime. I've also noticed other issues in my very small sample program.
Is there a way to do this that works, or is this a lost cause? And some background information on why would be appreciated.
Update: Thanks all for the replies, but I would like to have heard from someone who actually tried this and thought it was important. Although most of you told me it was a bad idea, I was not discouraged. I got a couple of programs working this way smoothly now. And plan to do this in all my flex apps. One trick seemed to work for me although I can't claim it'll work universally. If you need separate namespaces within your doc, take, HTTPService parameters for example, you could create a namespace within that element like so:
<HTTPService id="service" url="http://blah.com"
method="POST" result="gotResult(event)">
<request xmlns:p="*">
<p:param1>p1</p:param1>
<p:param2>p2</p:param2>
</request>
</HTTPService>
Hope this helps someone. I am very happy with how clean my code is now, almost as clean as a normal html file. As for people who think writing mx: throughout your code is clearer and what not, I disagree completely. I think languages that require you to repeat the same character sequence excessively in your code - which you should consider a document - have design flaws. Here's an analogy for you: how would you like it if you were reading an article on Barack Obama, and every single sentence contained the words 'Barack Obama', that would get pretty tiresome wouldn't it?
I think that removing the mx namespace will almost certainly cause you trouble with name conflicts as your project gets larger.
Personally I think the mx namespace makes the code clearer rather than more cluttered, especially if you have component based flex development or a lot of your own controls. Having owned a large flex code base for the last two years I find the mx namespace unobtrusive, especially when you have custom objects embedded inline such as item renderers.
My recommendation (unscientifically asserted) is to put up with it, especially if you are finding issues when removing it. I bet you'll stop noticing it after a while.
You need the mx or some xmls:[SOMETHING HERE] because that's the XML namespace that refers to the definition of the controls. It's like using namespaces in normal code.
Just writing Panel is ambiguous and could possibly conflict with another person's implementation of Panel. So we declare to Flex what namespace Panel belongs to (http://www.adobe.com/2006/mxml) and we alias it with mx.
Microsoft's WPF XAML requires this as well.
Just to be the voice of dissension...
In digging through Ely Greenfields code he does that a lot - I'm not sure if the other developers on the Flex SDK team do that but it does lend some credence to the argument for doing it...right?
I agree with the majority of other answers here, it is best to leave it. Eventually you will be wanting to use other namespaces for things such as custom components and you will need a namespace then for making the distinction. Then you will have some with a namespace and some without.
I would say if for no other reason, you should leave it because someday someone else might have to look at your code and they are probably going to find it much more readable with the mx than without.
The mx: is just a way to tell Flex that the Panel (along with any other component) is a part of the Flex framework, that it, built-in in Flex. This helps Flex to know where to look for the Panel, and will make your compiling process faster.
You can also use local: to access components that YOU created. Example: If I want to add some functionality to my Panel, I would type some code, and save it as a customized Panel, dubbed MyPanel. Them, I can use to tell Flex that MyPanel is my component, and it can find if somewhere in my project. Of course, you can name it anything you want :-)
I agree with you that the mx: looks unsightly at first, especially when you already have a strong background in HTML or XML, but you'll get used to it.
Keep in mind that if you are developing applications that should run on all kinds of platforms including mobile devices it is best to stick with pure spark as far as possible as it is supported on most mobile devices these days. There are cases where one is forced to use an mx control like an Accordion for instance. In this case if you do have time to implement it, it is wise to use tools or the basic controls in spark to create these more advanced or complicated controls to use instead.

Resources