Ted Patrick > { Events & Community } > Adobe Systems


Code-Behind in Flex 2

Microsoft languages typically implement a Code-Behind development model. Code-Behind allows you to separate user interface and application logic into classes that inherit from one another. This is a useful model and is easy to implement within Flex 2. So for anyone dreaming of Code-Behind in Flex 2, today is your lucky day. ;)

Code-Behind is just inheritance where the UI extends the application logic class, the Code-Behind. In Flex, since MXML generates an ActionScript Class, this provides the key to implementing Code-Behind. Onward!

Here is a simple example:

FlexCodeBehind Example

FlexCodeBehind Download

Step 1: Make a new Flex Project named "FlexCodeBehind".

Step 2: Make a new ActionScript Class like so:

package: app
class name: MyClass
extends: mx.core.Application

code:



Step 3: Modify "FlexCodeBehind.mxml" to inherit from app.MyClass like so:



In MXML, the root tag extends the listed class, this is how you denote inheritance in MXML. In this case, we use the app.MyClass as the root tag which inherits from mx.core.Application. This makes the application an instance of FlexCodeBehind.mxml so all methods, properties, and events within FlexCodeBehind.mxml, app.MyClass, and mx.core.Application are there.

Also note how the new 'app' namespace is used in the MXML document. The xmlns:app denotes the path to MyClass or "app.*" just like an import statement. This is handy if you want to add in custom components within other packages and it is a key element of understanding MXML as a language.

Advantages:
1. Code in classes and UI in MXML.
2. Easy to understand.
3. Reusable.

MXML is very deep as a language. It provides a high level declarative tag based language atop ActionScript 3 (ECMA Standard) and allows for components and classes to work hand in hand via composition. Over time I have come to appreciate the subtleties in MXML and ActionScript as they work perfectly together. The twist comes when you realize that there is no different between MXML and ActionScript 3 classes, they are just classes and are 100% interchangeable. I will post some examples of this in follow-up posts.

ASP.NET Code-Behind Information - Note the similarities...

So there you are, Code-Behind in Flex.

Cheers,

Ted :)

39 Responses to “ Code-Behind in Flex 2 ”

  1. # Blogger Eric

    I totally agree with this methodoloy, but I would suggest to go a step further and assign events within the actionscript too. in this way you can associate event handling with where you assigned the events, edit those behaviors and assignments, and totally close the view for editing.

    My Blog  

  2. # Blogger Matt

    Yep, you can assign events in the AS part, and you can even declare the variables in the AS class and then assign them in the MXML subclass.  

  3. # Blogger Eric

    something like this

    //button in mxml with id of myButton
    //must be declared as public to be properly inherited of course
    public var myButton:Button;

    public function initListeners():void{
    myButton.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
    }

    //handle the mouse event that has been assigned from actionscript
    private function handleMouseUp(e:MouseEvent):void{
    Alert.show("You just clicked the button");
    }

    within the xml you'd have

    mx:Button id="myButton" label="Click me!"/
    (sorry the blog wouldnt allow me to declare it as a tag)

    My Blog  

  4. # Anonymous Anonymous

    In .NET your .aspx and .cs files can have the same name but that is not the case with MXML and AS, correct? That is a bit annoying if that is indeed the case.  

  5. # Blogger Eric

    from my experience, it confuses flex to do so, yes.
    I use this naming convention

    MyClassBase.as
    MyClass.mxml

    My Blog  

  6. # Blogger Ted Patrick

    KISS. I like to keep things simple. Denoting click events within MXML is simple and much easier as it accomidates instanciation order and works with the States features.

    I do see your point. I wish it was easier to subscribe to events from within an AS3 Class.

    Maybe something like so:

    [Listener(type="click", target="myButton")]
    private function myButton_click( event:MouseEvent):void
    {
    //logic here
    }

    Tieing this into Meta makes sense from a product perspective as this is a means to automate code gen and simplify development.

    The worst case is to automate things and break workflow for some and not others. There are 1000 ways to do something, many are valid but it depends on the circumstances.

    My 2 cents,

    ted :)  

  7. # Blogger Eric

    Yup I see your point to, and doing it this way can cause a big mess when working with states. It's still normally the convention i stick with tho  

  8. # Anonymous seb

    I tried that but i had an issue when it came to refer the button from the mxml in to the actionscript. the actionscript doesn't seem to know about the id used in the mxml.
    Is there way of making the actionscript know abou the mxml?  

  9. # Blogger Eric

    Yup I see your point to, and doing it this way can cause a big mess when working with states. It's still normally the convention i stick with tho  

  10. # Blogger Eric

    @seb
    the mxml inherits from the actionscript, so you have to define a public variable, as i demonstrated up there which is the same as the id of the button within the mxml, then the mxml inherits events assigned to that button in actionscript  

  11. # Blogger Kenneth

    Is that TextMate (FlexMate...) I see instead of Flex Builder? I may be headed down that road as well as I see my trial of Builder is about to expire.  

  12. # Blogger Ted Patrick

    MXML generates an AS class at compile-time switching the file from .mxml to .as. This is the collision you are seeing and it is annoying in one sense and helpful in another.

    MXML is code gen to AS3 classes. So it allows direct use of MXML as AS3 Classes like so:

    MyComponent.mxml

    myCom:MyComponent = new MyComponent()

    This feature set if 100% legal and ready to roll. The annoying part of that MXML and AS classes can collide at compile time. The MXML and AS3 naming is problematic but it is a double edged sword.

    Ted :)  

  13. # Blogger Ted Patrick

    That is FlexBuilder not TextMate! (Although I have TextMate installed, it rocks).

    Ted  

  14. # Blogger Ted Patrick

    You will need to denote class members and their type to use them within an AS3 Code-Behind. Standard OOP in play here.

    Ted :)  

  15. # Blogger Místico

    Great Post Ted!!!!

    I am from the world of .NET and this examples illustrate very clear the concepts explained!!  

  16. # Blogger Chen Bekor

    actualy, I would prefer to use a more robust framework that seperates the UI from the Logic - Cairngorm is a great framework for doing that. The problem with the "code behind" approach is that the "code behind" is acting like a page controller. MVC model II frameworks like Cairngorm are based on a Front Controller approach wich is much more modular and flexible.  

  17. # Anonymous Dirk Eismann

    IMHO, the current approach of using code-behind adds unnecessary inheritance (and bytecode) just for the sake of separating MXML code from AS code while in the end, the MXML code gets turned into AS code prior compilation anyway.

    It would be nice if Flex 2.5 / 3.0 would natively support the seperation of AS and MXML. For example, you could create a MXML class and an AS class, both with the same name (Foo.mxml and Foo.as) and the same level of visibility for all members. During compilation, both code bases would then get merged into the runtime class definition for class Foo. That would be sweet - and very flex-ible :)  

  18. # Anonymous Tink

    dirk Flex does natively support the sepertation of AS and MXML through the 'source' property of the Script tag.

    What we are seeing here is inheritance. It isn't code behind, there's a class behind. This has disadvantages over the 'source' property in a Script tag.

    1. You designer needs to look at your class to see what your extending, or tell you want to extend in your superclass.
    2. It ruins inheritance. Your designer should be able to choose what they want to extend and it shouldn't matter to the logic what they want to extend.
    3. You don't end up with code-behind in this method. In fact you don't even end up with just a class-behind, you actually end up with a View class behind. You could actually create an instance of the (so called) code behind and add it to a display list. It has to be a View class because its the only class your View component can extend. Nasty!  

  19. # Anonymous Anonymous

    There is an alternate approach here, and that is to use ViewHelpers. Create a ViewHelper class (need not extend off anything if you dont want to ) for your View and then use composition to include it in your View. So in MyView.mxml...

    my:MyViewHelper view="{this}"

    and in MyViewHelper you can have a strongly typed variable that holds a reference to the view

    public var view:MyView

    I find this approach better because you get better support for compile time checking and there is no need to declare propeties of the View in the Helper. Also feels more flexible. I beleive this is the approach used in Cairngorm.  

  20. # Anonymous seb

    @Eric
    Thanks, it worked! i guess i can tell i am newbie wit that one as it's probably commun knowledge amongst flexers  

  21. # Blogger Patrick

    @Anonymous:
    I believe methods serve a different purpose and both can be used on a single view if you want.

    The ViewHelper is used to update the view without the interaction with your application model. This means it is used to update one or two propertues of your view.

    With code-behind you seperate logic and interface of your view. The only questionable about this method is if it object-oriented-wise a neat way to do it.  

  22. # Blogger shi11

    Code Behind is a very smart approach for flex apps. In particular for debugging. It keeps the Class.mxml super clean and quick to read and the ClassBase.as focussed on logic. No long pages of mixed code. No clunky script tags. As a convention we've banned the use of script tags. Both .as and .mxml files live next to eachother. Once the MXML is done, it mostly stays closed.  

  23. # Anonymous Robert Penner

    @eric, re: "you have to define a public variable"
    A protected variable will work as well; it's accessible in subclasses. This is what ASP.NET uses in its code-behind.  

  24. # Blogger expertseries

    Anyone looking for a full example be sure to check out the new article building components using code behind over on adobe devnet. Ted, thanks for the post, I've just started exploring Flex this weekend.  

  25. # Anonymous Steve Schelter

    As mentioned before, the mx:states tag no longer works properly when implementing code-behind. However, the solution is just a matter of namespace issues. Replace the "mx" namespace with the namespace that correlates to your code-behind class. So taking Ted's example, you would use app:states  

  26. # Anonymous Steve Schelter

    @Robert Penner: Normally, protected namespace should work for declaring components in the code-behind, however there's currently a bug in flex that does not permit this.  

  27. # Anonymous Anonymous

    Sometimes when I try to do code behind, somehow flex builder doesn't recognize it and sends me a lot of errors cause it cant find the methods or variables from the mxml to the as class and vice versa.
    However if I run the project it works is just that flex builder doesn't like the way it is :s
    I might be missing something that's my guess

    Does anyone have had the same problem ?  

  28. # Blogger Dr

    In a word - Sweet! Thanks Ted, that did it for me in under 30 seconds.  

  29. # Blogger mooooses

    Code behind appears at a high level to be a good thing because you see it for the first time and say, "Wow, I never thought of doing it like this." The real-world reality is that it sucks. It adds several levels of complication without providing any benefit.

    Once you've implemented a code-behind application, any UI changes will have to be edited in two files because UI elements have to be declared in your code file. It keeps the mxml file looking clean, but who cares what it looks like if it's actually more complicated since none of your UI elements can be anonymous. Furthermore, anybody following behind you will have to figure out the strange structure.

    Do yourself and everyone else a favor, and stay away from this masturbation technique.  

  30. # Anonymous Anonymous

    I am really new about Flex 2 and found the code-behind idea very interesting. Tried to follow the instruction to compile the simple code but seem not be able to get this running. What I did was FlexCodeBehind.mxml (the same code as posted), then MyClass.as under app dir (again the same code as posted). Tried to mxmlc FlexCodeBehind.mxml, the compiler complained that " A file found in a source-path must have the same package structure 'app', as the definition's package, 'app.MyClass'". Can someone help? Do I miss another file something? Thanks.  

  31. # Blogger Ted Patrick

    make sure to add the xml namespace! This is an import statement that allows the compiler to locate the AS class denoted in the root tag.

    Regards,

    Ted :)  

  32. # Anonymous Anonymous

    Ted, thanks for the reply. Yes, I had the xmlns in there as:

    xmlns:app="app.*"

    the compiler actually found MyClass.as. it is something else I did not do right.  

  33. # Blogger Ted Patrick

    The only other error I have seen is having an MXML and AS class named the same name. As MXML generates an AS3 class, this causes lots of problems. Do you have a MyClass.mxml document?

    Regards,

    Ted  

  34. # Anonymous Anonymous

    no, i do not have MyClass.mxml. My file structure is the following:

    currentDir
    MyClassTest.mxml

    currentDir/app
    MyClass.as

    thanks.  

  35. # Anonymous Anonymous

    okay, finally.

    in MyClass.as file, add in the path of the package:

    package app
    {
    .
    .

    }  

  36. # Blogger john_r_nyquist

    Great info, thanks for posting.  

  37. # Anonymous Anonymous

    This method is not perfect.

    Consider if you need to get a reference to your application level class along the lines of:

    public static function getInstance():MyClass {
    ...
    }

    You will no longer have access to the elements of the FlexCodeBehind.mxml "object"

    Casting does not seem to work, as far as I can tell.  

  38. # Anonymous Federico

    As posted previously, I fully agree that code behind as a concept sucks. Once you start coding in different places to deal with the same things you know something is going wrong. Adding code inside CDATA blocks is even worse.
    So... is there some guideline on how to make polished programmatic flex app? Should I just override the initialize method and add all my controls there? I only see mxml tutorials there days... :(  

  39. # Anonymous GaB

    I had a problem with CB (code behind) and "states". Compiler gives me a 1009 error when I do from the CB class:

    currentState="whatever"

    And looking at the states properties found that all the targets were nulls, so I declared the (custom) components in the CB class as [Bindable].
    This was the only way I found to make it work.  

Post a Comment



Jobs


Flex Jobs
city, state, zip


© 2008 Ted On Flash