Looking at the world of media: from music to RIA.

The Flex Code-Behind Pattern

April 22nd, 2008 Posted in ActionScript, Flex Development, Rich Internet Applications, web integration

Flex LogoThe Flex code-behind pattern is a design pattern that has been around since the release of Flex 1.0 yet is not known or used by a lot of developers. The initial concept of the pattern was based on the ASP.NET development pattern where the layout is handled in a main file and a secondary “backing” file handles all the logic. The goal of the pattern is to create a clear separation of logic and layout.

History Of The Code-Behind Pattern
This pattern was first applied in Flex 1 and 1.5 through a “feature” in the Flex compiler where two same named files would be merged into a single class. To leverage this the developer would create an MXML file that defines the layout and then an ActionScript logic class, which would have the same name as the MXML file, was used to handle all of the logic. At compile time the Flex compiler would take the MXML and the ActionScript and then merge them together using a process called mixins.

The original version of Flex was built in AS2 which enabled mixins during the compile process. A mixin is the ability to dynamically merge multiple classes into a single class without requiring inheritance. Its similar to implementing an interface but instead of having to code the methods to conform to the interface, mixins directly add the functionality in. Its a strange hybrid of inheritance, implementation and composition that is used in prototype based languages like JavaScript.

With the advent of ActionScript 3, mixins went away because the language moved from a prototype based structure to a stricter inheritance model. When this happened the “feature” that handled the MXML to Class code merge was “fixed” and stopped the initial form of code-behind. Once this “fix” was found by the development community there was a lot of concern about how the Flex team removed a powerful feature. This was an understandable concern yet the ability to handle mixins was no longer a feature of the language. The reason this no longer worked is that the compiler saw the MXML file and the backing class as a namespace conflict. From the compilers point of view you now had two different classes yet they where identically named, which is not allowed.

What Goes On Behind The Scenes
Whenever I give trainings on Flex to new developers one of the first things I talk about is the differences between MXML and ActionScript. When you first learn Flex there is often confusion between what MXML is and how it relates to ActionScript. We tend to think of it as different entities, but the reality is MXML is just an abstracted form of ActionScript. MXML is a declarative XML syntax that is converted by the compiler into an ActionScript class. This is an important concept to understand because this is the root of why the compiler throws an error when trying to have a MXML file and an ActionScript File with the same name in the same package. The MXML file is really just an ActionScript class and therefore we have a conflicting namespace error.

To help visualize this, imagine the root node of the MXML file is the same as an extends statement. When we use something like this in MyApp.mxml:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
	...
</mx:Application>

We are really saying:

public class MyApp extends Application

So why do we need MXML syntax if it just becomes ActionScript. As you are probably well aware, doing complex layout in ActionScript takes a ton of code, especially when you get into the world of nested layout. It can be done in code but why would you want to? XML is all about parent/child hierarchies and by using this as a layout language you can quickly define complex organizational structures that would have taken hundreds of lines of code if you did it all in ActionScript. Now that we have a better understanding of the MXML/ActionScript relationship we can start talking about how the pattern is implemented.

The Pattern Structure
When looking at Adobe’s MXML examples we often see them using the <mx:Script> tag to define any ActionScript that is required to make the MXML example work. This approach is fine for simple examples but once we begin development of a larger application using Flex, having all the MXML logic in a single <mx:Script> tag becomes unwieldy. Even if the code is written by the most organized developer, once you hit 300+ lines of ActionScript with 100 lines of MXML it becomes hard to see the forest from the trees.

One way to solve this is to use the source attribute in the <mx:Script> tag and set it to an external AS file. This helps because you now have separated all your ActionScript out of the MXML but now you have externalized AS files that aren’t really classes, that sit in the file structure and you can’t extend from them.

The Code-Behind pattern is a solution to this issue. The first step is to create an ActionScript class that extends the base type that you want your MXML file to be. For example, a Canvas:

package com.vivisectingmedia.demo
{
	import mx.containers.Canvas;
 
	public class MyComponentLogic extends Canvas
	{
 
	}
}

I have now created a Class in the com.vivisectingmedia.demo package that extends from Canvas. This is my backing logic class that my MXML extends from. Note that I have used the postfix “Logic” to create a unique name. If you recall, our MXML and AS have to be different names. I prefer the “Logic” postfix but you can use “Base” or “Backing” or any other postfix/prefix you like. Now, you can create the MXML file. In this example let’s assume the MXML component is in the same package as the ActionScript:

<MyComponentLogic
 	xmlns="com.vivisectingmedia.demo.*"
	xmlns:mx="http://www.adobe.com/2006/mxml">
	...
</MyComponentLogic>

This code would be in an MXML file called MyComponent.mxml. The MXML now extends from the ActionScript and we can begin to start laying out content and adding logic as needed.

Naming Conventions And Things To Consider
If you follow this patten there are a few gotchas you need to be aware of. These issues may feel a little limiting at first, but after using this on many projects it has become second nature for me and I have yet to be blocked or discouraged by any of the potential challenges. Here is some example code that I will be relating to for the following points:

package com.vivisectingmedia.demo
{
	import flash.events.MouseEvent;
 
	import mx.containers.Canvas;
	import mx.controls.Button;
 
	public class MyComponentLogic extends Canvas
	{
		[Bindable] public var my_button:Button
 
		// Constructor
		public function MyComponentLogic()
		{
			super();
		}
 
		override public function childrenCreated():void
		{
			super.childrenCreated()
			my_button.label = "do something..."
		}
 
		public function handleMouseEvent(event:MouseEvent):void
		{
			// do something
		}
 
	}
}
<MyComponentLogic
 	xmlns="com.vivisectingmedia.demo.*"
	xmlns:mx="http://www.adobe.com/2006/mxml">
 
	<mx:Button id="my_button" click="handleMouseEvent(event)">
 
</MyComponentLogic>

Remember that the MXML inherits from the base logic class. What this means is that as you add children components to the MXML and you want the ActionScript Logic to manipulate them you have to make sure the ActionScript has them declared. To declare them you have to define properties in the ActionScript class whose name matches the component id you use in the MXML. For example, look at the Button id in the MXML above and notice that I have a public property in the ActionScript with the same name. The property must be public in the ActionScript class and you should mark them as [Bindable] so that if you have other components binding to them the change watcher system still operates as expected.

This works because the MXML file is an extension of the base logic class and the components with the matching id is equivalent to overriding the properties in the ActionScript. You may wonder why the properties have to be public and not protected if this is an override. The issue is that the MXML components are not part of the MXML class, they are children of the MXML class. Since they are children they do not have access to the ActionScript class’ protected methods and the compiler will see their id as a duplicate name for the MXML class, which is invalid. If the method is public, the compiler interprets this MXML component id as an override and it works. So, long story short… always make the properties [Bindable] public.

Never try to manipulate the children components from the ActionScript constructor. This is a common mistake made by developers using this pattern. For example, you try to set the button label in the constructor. If you tried this you would get a null value error for the button since it has not been created yet. MXML creates the children components in the createChildren() phase so the best way to work around this is to override childrenCreated() method that is executed once all the children in the entire inheritance stack has been created. In this method you first call super.childrenCreated() and then you can start accessing children components.

Never try to removeChildren() that are defined in MXML. This is a mistake that sometimes works when you try it but in most cases this just causes a lot of heartache. Usually the heartache occurs after you have been doing this for a while and you then have to go back and fix a lot of code that was dependent on the first removeChild(). Unfortunately I have seen this first hand and its not a pretty sight. If you are doing a lot of children manipulation then you will want to move away from MXML declaration and handle the children creation/removal all in ActionScript.

Name your components using a different convention. This is not a requirement but it will help out in the long run. On my projects we use all lower case with underscores between the words (ex: my_button) to identify a component in the MXML. Camel case (ex: myVarName) is used for public and protected properties. I am an old school Flash developer so I use a single underscore (ex: _privateVar) for private variables and double underscores (ex: __myGetterSetter) for private properties that are exposed via a getter/setter. By using this kind of naming convention it makes reading your code easier to determine what is being manipulated and when.

Try to avoid mixing and matching MXML and ActionScript event/action binding. This is also more of a recommendation then a requirement. If you start binding the creationComplete or click events in MXML try to bind them all in MXML. If you bind your events in ActionScript try to bind all of them in ActionScript. In my above example I bind the click event via MXML. You can easily do this in ActionScript within the initilize() method using addEventListener(). Once you start mixing and matching it can be hard to track down code flow later on. You may find yourself wondering why an event keeps triggering yet it appears to not be referenced any where in your ActionScript. The problem ends up being that you used event declaration for that one type in MXML and forgot about it. Use what works best for you.

Code Behind allows for continued extending One issue with MXML is that you can only extend MXML from MXML. Once you have moved code/logic over to MXML and then you want to extend from it, you can not use an ActionScript class to extend from the MXML. I have seen some pretty ugly hacks, or even worse; mass duplication of code, because developers are attempting to extend or replicate most but not all of the functionality from an existing component. By moving logic into a backing ActionScript class, this means that only layout is defined in the MXML, from there you can extend from the base ActionScript class, add new functionality, and then add your layout. This is one benefit that I feel a lot of developers miss. For applications that mature and/or grow having a more robust pattern like Code Behind, can enable easier maintenance and additions without having to get into some crazy hacks of removing/hiding children from extended MXML files, or just copy and pasting an existing file and then making the required modifications.

In Conclusion
The Code-Behind Pattern is a relatively simple pattern that can provide a clean code structure which makes your code base a lot easier to manage over time. I have to admit that I was pretty hesitant when I was first required to use this pattern on a large project. It seemed like a lot of extra work but once we started getting into extremely complex components and layout this functionality was extremely powerful. Not only was the code cleaner but if you focus on abstracting your Logic base classes you can easily extend and swap out the interface. Its a lot easier to extend from a core AS class then trying to extend from the MXML and having to modify the layout. Try it out on your projects and please post your comments about your success or challenges using this in development.


revisions:

  • April 29th, 2008: fixed a few grammatical errors and added clarifications to the “gotchas” section to help explain why the recommended solutions work.

  • April 4th, 2009: fixed more grammatical issues and added a section about extending classes/mxml

  • October 9th, 2009: fixed typo in package name and updated references to initialize() to replace them with createChildren(). For more information why, read the DevelopmentArc white-paper on The Flex Component Lifecycle that I helped write.

  1. 12 Responses to “The Flex Code-Behind Pattern”

  2. By webnesto on Apr 25, 2008

    Having worked with James on a project that implemented this pattern, I can heartily agree with his recommendations and personally attest to the value in this structure.

    For people new to this concept, I always refer them to how we try to create unobtrusive javascript in a traditional HTML/JS environment.

  3. By Brent on Apr 29, 2008

    Excellent article. Tried this pattern a couple of times (using some code from the Ted-On-Flex blog – http://www.onflex.org/ted/2007/02/code-behind-i...), but have always found several pitfalls. This seems to clarify a number of my questions. Thanks!

  4. By James on Apr 29, 2008

    I am glad this helped clear up some of the pitfalls. When we first adopted this pattern on the project Webnesto is referring to in his comment, we would definitely had some challenges with the initial implementation. I have a feeling I missed a few other less common pitfalls we stumbled upon during the that project and other ones I have have used it on. At this point it has become more second nature, so what was once an “workaround” is now just how I code. If you, or anyone else, has some issues or questions about the pattern please let me know and I will reply and/or update the post with recommendations.

  5. By Rafael Santos on Aug 29, 2008

    Fantastic article….. Good straight forward information…. Direct and compact….
    It helped me understand more about how Flex/AS works and how this interaction should be handled….
    Thanks

  6. By Emre Selen on Oct 18, 2008

    That was just the case I was wondering about. Thanks a lot. Nice and simple. Just on point.

  7. By artigat1 on Aug 5, 2009

    I like the idea of this code behind a lot. One problem I seem to be having though is creating a new instance of an object in actionscript code and then trying to set elements within the mxml for that object.

    It seems that I need to add the object before I can change any of the elements or properties. Is that correct? The project I'm working on requires a number of objects to be set in memory ready to be added when required. This might include setting the text of a label, but also it's position or styles or any number of other things.

    I've tried moving the super.initialize() into the constructor, but that doesn't seem to work. Have you encountered this problem before?

  8. By rdeman on Sep 24, 2009

    Very nice introduction to the Code Behind pattern in Flex. 1 question: setting the width, height framerate, etc. do no longer work in the MXML main file :-/

  9. By James Polanco on Sep 24, 2009

    rdeman, That should not be the case, we use the code behind for the root Application MXML file for all our projects and setting the width, height and framerate for the application in the MXML works fine.

    Are you overriding these with compiler statements? In the backing ActionScript? I would look for other causes that would block these values from being set via the MXML because the code-behind shouldn’t disable this.

  10. By James Polanco on Sep 24, 2009

    artigat1, Sorry for the late reply… catching up on a serious backlog of work.

    If you are checking back I would be curious to hear more about what you are trying to do. Are you trying to create objects via ActionScript and then set properties via MXML?

    I don’t think that will be possible since the MXML is causing the compiler to create the instances you define.

    Now, if you are talking about using states to manipulate objects you create, that should be possible, as long as you expose the property on the backing class as a public [Bindable] value. Then you can access this via MXML and call setProperty or such.

    To offer any more help I would need to see more concrete examples…

  11. By Jonathan on Sep 25, 2009

    So, when you defined your package name I believe that you’ve made a typo. Shouldn’t it read “com.vivisectingmedia.demo”? Good example this helped me a lot. Thanks!

  12. By Jovica Aleksic on Oct 9, 2009

    We are also using the code-behind approach in a large project, and I am quite happy with it too. It reminds me of PHP Smarty template engine, where you would write the logic in a php file, and the layout in a tpl file, where you would use html tags with variables in curly brackets, just as you do in Flex.

    The only “problem” I encountered with this approach is that you definitely always have to define a layout in MXML and copy-paste markup there, even if you could basically use most of the layout and components from another MXML file. So, say you have two quite similar components, in logic as well as in layout, just one of them has some button and some checkbox extra. You will extends the base class and add the two variables for checkbox and button, but for the MXML, you will have to copy all the markup, and additionally put the checkbox and button in there. Still, this is far better than workarounds like this one: http://loopmode.de/host/flex/ExtendedMxmlComponenentTest/ExtendedMxmlComponentTest.html http://loopmode.de/host/flex/ExtendedMxmlComponenentTest2/ExtendedMxmlComponentTest.html (it was a reply to a question of how to extends MXML-only components, replacing children)

    So, we use our base classes for all kinds of logic and extending, and in the end, the component always receives an own Layout definition in form of a MXML class. Would be fine if we could mix the approach of my example links with the code-behind approach, but I can’t think of a way at the moment.

  1. 1 Trackback(s)

  2. Apr 22, 2009: J2EE Code Behind for Flex / Actionscript Developers « timshaya

You must be logged in to post a comment.