Flex best practices

Im new to Flex but I have plenty of experience using traditional webdev technologies (HTML, CSS, JS/AJAX, PHP).  I know that when you build a web app using these technologies, it's considered best practice to use event listeners rather than event handlers in JS, and to place all your JS in an external file and reference it in your HTML page. I've been watching several videos on Lynda.com on Flash Builder 4 and Flex, and in all the videos, the author places most of the Actionscript in the MXML file while referencing a few custom Actionscript classes. With that said, what do Flex developers typically do?

In Flex 3, it is considered best practice to use the Presentation Model pattern (as advocated by Martin Fowler), where you extract the view states and view logic.
A PM is a simple ActionScript class that extends EventDispatcher (for Data Binding purposes).
[Bindable]
public class SalesProjectionPM extends EventDispatcher {
     // Collection of QuarterlySales objects
     public class quarterlySales:ArrayCollection;
     // Event handler
     public function viewSwitchHandler(event:MouseEvent):void {}
You can then inject this PM into an MXML view using an IoC container framework and bind your view to the corresponding PM for both your components dataProviders and events. If you have a central data model, you can inject it into your PM and bind to it.
In Flex 4, you already have the separation of view and logic that comes with the new Spark Architecture. You have an ActionScript component that contains the view states and view logic (including event handlers) on the one side. And you have a MXML skin that materializes the UI on the other.
You add/remove event handlers in the partAdded(), partRemoved() overriden methods. If you have a central data model, you can inject it into your ActionScript components.

Similar Messages

  • Using XML with Flex - Best Practice Question

    Hi
    I am using an XML file as a dataProvider for my Flex
    application.
    My application is quite large and is being fed a lot of data
    – therefore the XML file that I am using is also quite large.
    I have read some tutorials and looked thorough some online
    examples and am just after a little advice. My application is
    working, but I am not sure if I have gone about setting and using
    my data provider in the best possible (most efficient) way.
    I am basically after some advice as to weather I am going
    about using (accessing) my XML and populating my Flex application
    is the best / most efficient way???
    My application consists of the main application (MXML) file
    and also additional AS files / components.
    I am setting up my connection to my XML file within my main
    application file using HTTPService :
    <mx:HTTPService
    id="myResults"
    url="
    http://localhost/myFlexDataProvider.xml"
    resultFormat="e4x"
    result="myResultHandler(event)" />
    and handling my results with the following function:
    public function myResultHandler(event:ResultEvent):void
    myDataFeed = event.result as XML;
    within my application I am setting my variable values by
    firstly delacring them:
    public var fName:String;
    public var lName:String;
    public var postCode:string;
    public var telNum:int;
    And then, giving them a value by “drilling” into
    the XML, E;g:
    fName = myDataFeed.employeeDetails.contactDetails.firstName;
    lName = myDataFeed.employeeDetails.contactDetails.lastName;
    postCode =
    myDataFeed.employeeDetails.contactDetails.address.postcode;
    telNum = myDataFeed.employeeDetails.contactDetails.postcode;
    etc…
    Therefore, for any of my external (components in a different
    AS file) components, I am therefore referencing there values using
    Application:
    import mx.core.Application;
    And setting the values / variables within the AS components
    as follows:
    public var fName:String;
    public var lName:String;
    fName =
    Application.application.myDataFeed.employeeDetails.contactDetails.firstName;
    lName =
    Application.application.myDataFeed.employeeDetails.contactDetails.lastName;
    As mentioned this method seems to work, however, is it the
    best way to do it??? :
    - Connect to my XML file
    - Set up my application variables
    - Give my variables values from the XML file ……
    Bearing in mind that in this particular application there are
    many variable that need to be set and there for a lot of lines of
    code just setting up and assigning variables values from my XML
    file.
    Could someone Please advise me on this one????
    Thanks a lot,
    Jon.

    I don't see any problem with that.
    Your alternatives are to skip the instance variables and
    query the XML directly. If you use the values in a lot of places,
    then the Variables will be easier to use and maintain.
    Also, instead of instance variables, you colld put the values
    in an "associative array" (object/hashtable), or in a dictionary.
    Tracy

  • Displaying Content in Flex - Best Practice

    I'm curious as to people's thoughts for the best methods to
    display content in Flex. In particular, I'm creating a UI and want
    one of the first panels that is displayed to the user to display
    some simple instructions on how to use the UI. Should I import HTML
    from an external file? Should I embed XML or HTML in the SWF? Or,
    should I simply code the content into the SWF? I want the content
    to be styled like the rest of my application - fonts, colors, etc.
    Any suggestions would be greatly appreciated.
    Thank you.

    You can embed the content in the swf (unless you want it to
    change).
    Then you can style it using standard css.
    This way the resulting application is modular, and if you
    change the css in the future, changes are reflected in all your
    styled components.
    More here:
    http://livedocs.adobe.com/flex/1/flex_builder_en/wwhelp/wwhimpl/common/html/wwhelp.htm?con text=Using_Flex_Builder&file=brady510.htm

  • Flex Best Practices-Transitions

    What would be the best way to transition from a small login
    screen to a full application once the user has been verified? The
    best example that I could find uses flex's base states
    http://www.vipercreations.com/media/tutorials/login_system_with_flex_and_php/
    (Login with user:test,pass:test)
    I don't think thats the wrong way to do it, but I don't know
    if its the best.

    well, i do it this way
    public function login(userId:String, password:String):void
    var url:String = "
    http://"+GeneralSettings.SERVERIP+":8080/login.do";
    var request:URLRequest = new URLRequest(url);
    var variables:URLVariables = new URLVariables();
    variables.userId = userId;
    variables.password = password;
    request.data = variables;
    request.method = URLRequestMethod.POST;
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, requestWsdls);
    loader.load(request);
    }

  • Best practice for adding text to Flex container?

    Hi,
    I'm having some troubles to lay a TextFlow class out properly
    inside a Flex container. What's the best practice to achieving
    this, for example adding a lot of text to a small Panel?
    Is it possible to pass anything other than a static width and
    height to DisplayObjectContainerController constructor, or is this
    not the place to implement this? I guess what I am looking for is
    the layout logic I'd normally pack into a custom Flex component and
    implement inside measure() and so on.
    My use case: a chat application which adds multiple TextFlow
    elements to a Flex container such as Panel. Or use TextFlow as a
    substitute for UITextField.
    Some example code would help me greatly.
    I'm using Flex 3.2.
    Regards,
    Stefan

    Thanks Brian, the example helps. However problems quickly
    arise if I modify it slightly to this (please compile it to see):
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" initialize="init()">
    <mx:Script>
    <![CDATA[
    import flashx.textLayout.compose.StandardFlowComposer;
    import
    flashx.textLayout.container.DisplayObjectContainerController;
    import flashx.textLayout.container.IContainerController;
    import flashx.textLayout.elements.TextFlow;
    import flashx.textLayout.conversion.TextFilter;
    private var _container:Sprite;
    private var _textFlow:TextFlow;
    private function init():void
    _container = new Sprite();
    textArea.rawChildren.addChild(_container);
    var markup:String = "<TextFlow xmlns='
    http://ns.adobe.com/textLayout/2008'><p><span>Hello
    World! Hello World! Hello World! Hello World! Hello World! Hello
    World! Hello World! Hello World! Hello World! Hello World! Hello
    World! Hello World! </span></p></TextFlow>";
    _textFlow = TextFilter.importToFlow(markup,
    TextFilter.TEXT_LAYOUT_FORMAT);
    _textFlow.flowComposer.addController(new
    DisplayObjectContainerController(_container, 200, 50));
    _textFlow.flowComposer.updateAllContainers();
    ]]>
    </mx:Script>
    <mx:Canvas width="100" height="100" id="textArea" x="44"
    y="46" backgroundColor="#F5EAEA"/>
    </mx:Application>
    What is the best way to make my textflow behave like a
    'normal' UIComponent in Flex? Should I use UIComponent instead of
    Sprite as a Container? Will that take care of resize behaviour?
    I have never before needed to use rawChildren.addChild for
    example, maybe you can explain why that's needed here?
    I realise that the new Textframework works on an AS basis and
    is not Flex or Flash specific, but this also poses some challenges
    for those of us using the Flex framework primarily.
    I think it would help to have some more basic examples such
    as using the new text features in a 'traditional' context. Say for
    example a TextArea that is just that, a TextArea but with the
    addition of inline images. I personally feel that the provided
    examples largely try to teach me to run before I can walk.
    Many thanks,
    Stefan

  • Best practice for auto update flex web applications

    Hi all
    is there a best practice for auto update flex web applications, much in the same way AIR applications have an auto update mechanism?
    can you please point me to the right direction?
    cheers
    Yariv

    Hey drkstr
    I'm talking about a more complex mechanism that can handle updates to modules being loaded into the application ect...
    I can always query the server for the verion and prevent loading from cach when a module needs to be updated
    but I was hoping for something easy like the AIR auto update feature

  • Best practices for "designer - developer" interaction in Flex Mobile

    Hi,
    I'm starting development of a mobile software application and Flex Mobile is the platform I've chosen for that.
    What is the best practice / recommended workflow for designer-developer interaction? For example in web application the designer provides HTML/CSS templates to the developer which integrates them in the Web Application. What is the analogue in Flex Mobile? What should I request as input from the designer?
    I'll appreciate any hints, links, advises or previous experience on the topic.
    Thanks!
    Best Regards,
    Dinko

    If you're using Adaptive Web Design (CSS3 media queries), you can maintain one site with CSS Layouts optimized for different device widths.
    http://www.adobe.com/devnet/dreamweaver/articles/introducing-media-queries.html
    jQuery Mobile
    http://jquerymobile.com/
    If you're actually running separate web sites for mobile and non-mobile devices, have a look at this recent discussion:
    http://forums.adobe.com/message/4177360#4177360
    IMO, there is nothing wrong with providing links for mobile and non-mobile users to choose which site they would prefer to use -- especially for tablets who may have an interest in both.
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists 
    http://alt-web.com/
    http://twitter.com/altweb

  • Best practice to embed flex application in html

    Hello guys
       I am not sure what's the best practice to embed the flex application. We couldn't use html code in flex builder. Would you guys edit the html files via other tools to embed the swf file after the application is completed or there are other ways to do it. Thanks for the reply.

    Hi Jerry,
    Why you couldn't use the html code generated in flex builder. In the html wrapper file generated in FlexBuilder you have SWF embed code directly along with the Flash Player detection javascript code...If your users don't have the FlashPlayer installed or if they don't have the latest Flash Player version installed then the  application will prompt the users to install the latest Flash player plugin..
    What's the problem that you have got by using the html wrapper file generated in FlexBuilder..
    Thanks,
    Bhasker Chari

  • Flex, PHP, MySQL Best Practices?

    When using the HTTPService to invoke PHP/ database
    transactions what are some best practices to insure multiple
    simultaneous users successfully complete the transaction?
    So, in my Actionscript I build an object to pass to the PHP
    script that uses the values of the object to build a SQL query and
    executes the query, evaluating the result.
    Right now, I'm returning a text string from the PHP script
    (after error checking there) that simply says "ok" if the script
    succeeded.. and using that string in the HTTPService.Result
    (lastResult) listener.
    Anyone have any experiences to comment on?
    thanks,
    Dan

    Or use AMFPHP and pass typed objects back and forth. I find
    this much easier than working with XML. Once you've used AMFPHP on
    one project, you'll wonder why you bothered with XML. Or at least
    that's how it was for me. AMFPHP 2.0 should be released very soon -
    I believe they're just getting the docs ready.
    Cheers,
    Darren.

  • Best Practice for FlexConnect Wireless roaming in MediaNet environment?

    Hello!
    Current Cisco best practice recommendations for enterprise MediaNet design, specify that VLANs be local to a switch / switch stack (i.e., to limit the scope of spanning-tree). 
    In the wireless world, this causes problems if you want users while roaming to keep real-time applications up and running.  Every time they connect to a new AP on a different VLAN, then they will need to get a new IP address, which interrupts real-time apps. 
    So...best practice for LAN users causes real problems for wireless users.
    I thought I'd post here in case there's a best practice for implementing wireless roaming in a routed environment that we might have missed so far!
    We have a failover pair of FlexConnect 7510s, btw, configured for local switching for Internal users, and central switching with an anchor controller on the DMZ for Guest users.
    Thanks,
    Deb

    Thanks for your replies, Stephen and JSnyder.
    The situation here is that the original design engineer is no longer here, and the original design was not MediaNet-friendly, in that it had a very few /20 subnets bridged over entire large sites. 
    These several large sites (with a few hundred wireless users per site), are connected to an HQ location (where the 7510s in failover mode are installed) via 1G ethernet hand-offs (MPLS at the WAN provider).  The 7510s are new, and are replacing older contollers at the HQ location. 
    The internal employee wireless users use resources both local to their site, as well as centralized resources.  There are at least as many Guest wireless users per site as there are internal employee users, and the service to them consists of Internet traffic only.  (When moved to the 7510s, their traffic will continue to be centrally switched and carried to an anchor controller in the DMZ.) 
    (1) So, going local mode seems impractical due to the sheer number of users whose traffic bound for their local site would be traversing the WAN twice.  Too much bandwidth would be used.  So, that implies the need to use Flex / HREAP mode instead.
    (2) However, re-designing each site's IP environment for MediaNet would suggest to go routed to the closet.  However, this breaks seamless roaming for users....
    So, this conundrum is why I thought I'd post here, and see if there was some other cool / nifty solution I wasn't yet aware of. 
    The only other (possibly friendly to both needs) solution I'd thought of was to GRE tunnel a subnet from each closet to the collapsed Core / Disti switch at each site.  Unfortunately, GRE tunnels are not supported in the rev of IOS on the present equipment, and so it isn't possible to try this idea.
    Another "blue sky" idea I had (not for this customer, but possibly elsewhere in the future), is to use LAN switches such as 3850s that have WLC functionality built-in.  I haven't yet worked with the WLC s/w available on those, but I was thinking it looks like they could be put into a mobility group, and L3 user roaming between them might then work.  Do you happen to know if this might be a workable solution to the overall big-picture problem? 
    Thanks again for taking the time and trouble to reply!
    Deb

  • Best Practice - WAP connecting switchport configuration.

    Is there a best practice for deploying the WAP's in a WAP/WLC infrastructure?  Should the connecting switchport be an Access port or a Trunk port?  I've seen this implemented in both fashions and wasn't sure if one was a better choice than the order.  What is the difference?
    My other question is regarding applying additional switchport configurations.  Is there anything wrong with applying either spanning-tree portfast, spanning-tree bpdguard, or switchport port-security. 

    Hi Ken,
    Access port all the time, everywhere, UNLESS the AP is configured for HREAP/FLEX then trunk. Or if you deploy a AP in monitor mode then TRUNK.
    QOS -- if its access port trust dscp. If you truck trust cos.
    No you are fine. Portfast is highly recommended.
    "Satisfaction does not come from knowing the solution, it comes from knowing why." - Rosalind Franklin
    ‎"I'm in a serious relationship with my Wi-Fi. You could say we have a connection."

  • Best Practice: Storing an array in MySQL

    Hi,
    I'm working on an app that uses Flex 2, Coldfusion and MySQL.
    I'd like to store an array (or in this case an ArrayCollection)
    into my db. I'm not totally sure if I can do this. I read something
    about PHP having an implode command but I'm wondering what the best
    practice would be for trying to get an array into MySQL via
    ColdFusion.
    I'd be grateful for any advice.
    Novian

    Thanks, mike_the_maven.
    I'm not familiar with that tag but I'll definitely look into.
    I'm also wondering about potentially storing my ArrayCollection as
    a BLOB in MySQL. Any thoughts about this approach?
    Thanks.
    Novian

  • Best practice for Spark repeating background image in a SkinnableContainer?

    In my old Flex 3.5 code I would accomplish this by dropping an Image into a Canvas and hitting the Canvas with some css style stuff to get the repeat.  The Image tag had a source property that would take a web address so I could dynamically grab different images from the web based on some conditions.  Little bit more trouble with Flex 4.5 and Spark but I'm trying to get there.
    Here Adobe docs explain how to *embed* a background image:
    http://help.adobe.com/en_US/flex/using/WS422719A4-7849-4921-AF39-57FF567B483B.html#WS063B0 491-B7AB-4b00-A39F-E44310BCB0E0
    They use a BitmapFill object in the skin.
    <!-- background fill -->
        <s:Rect id="background" left="3" top="3" right="3" bottom="3" alpha=".25">
            <s:fill>
                <s:BitmapFill source="@Embed(source='../../assets/myImage.jpg')"/>
            </s:fill>
        </s:Rect>
    Problem is I need to do this without embedding the image.  In my old code I grabbed the image from web (set source property on Image tag to web address).  What's the best practice for achieving this with a skinnable container?  The BitmapFill object used above won't take a web address for a source.
    Thanks in advance.

    Use BitmapImage with a fillMode of repeat:
    <s:BitmapImage source="http://www.google.com/intl/en_com/images/srpr/logo2w.png" width="100%" height="100%" scaleMode="stretch" fillMode="repeat" />

  • Best practice for lazy-loading collection once but making sure it's there?

    I'm confused on the best practice to handle the 'setup' of a form, where I need a remote call to take place just once for the form, but I also need to make use of this collection for a combobox that will change when different rows in the datagrid or clicked. Easier if I just explain...
    You click on a row in a datagrid to edit an object (for this example let's say it's an "Employee")
    The form you go to needs to have a collection of "Department" objects loaded by a remote call. This collection of departments only should happen once, since it's not common for them to change. The collection of departments is used to populate a form combobox.
    You need to figure out which department of the comboBox is the selectedIndex by iterating over the departments and finding the one that matches the employee.department.id
    Individually, I know how I can do each of the above, but due to the asynch nature of Flex, I'm having trouble setting up things. Here are some issues...
    My initial thought was just put the loading of the departments in an init() method on the employeeForm which would load as creationComplete() event on the form. Then, on the grid component page when the event handler for clicking on a row was fired, I call a setup() method on my employeeForm which will figure out which selectedIndex to set on the combobox by looking at the departments.
    The problem is the resultHandler for the departments load might not have returned (so the departments might not be there when 'setUp' is called), yet I can't put my business logic to determine the correct combobox in the departmentResultHandler since that would mean I'd always have to fire the call to the remote server object every time which I don't want.
    I have to be missing a simple best practice? Suggestions welcome.

    Hi there rickcr
    This is pretty rough and you'll need to do some tidying up but have a look below.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
            <![CDATA[
                import mx.controls.Alert;
                import mx.collections.ArrayCollection;
                private var comboData:ArrayCollection;
                private function setUp():void {
                    if (comboData) {
                        Alert.show('Data Is Present')
                        populateForm()
                    } else {
                        Alert.show('Data Not')
                        getData();
                private function getData():void {
                    comboData = new ArrayCollection();
                    // On the result of this call the setUp again
                private function populateForm():void {
                    // populate your form
            ]]>
        </mx:Script>
        <mx:TabNavigator left="50" right="638" top="50" bottom="413" minWidth="500" minHeight="500">
            <mx:Canvas label="Tab 1" width="100%" height="100%">
            </mx:Canvas>
            <mx:Canvas label="Tab 2" width="100%" height="100%" show="setUp()">
            </mx:Canvas>
        </mx:TabNavigator>
    </mx:Application>
    I think this example is kind of showing what you want.  When you first click tab 2 there is no data.  When you click tab 2 again there is. The data for your combo is going to be stored in comboData.  When the component first gets created the comboData is not instansiated, just decalred.  This allows you to say
    if (comboData)
    This means if the variable has your data in it you can populate the form.  At first it doesn't so on the else condition you can call your data, and then on the result of your data coming back you can say
    comboData = new ArrayCollection(), put the data in it and recall the setUp procedure again.  This time comboData is populayed and exists so it will run the populate form method and you can decide which selected Item to set.
    If this is on a bigger scale you'll want to look into creating a proper manager class to handle this, but this demo simple shows you can test to see if the data is tthere.
    Hope it helps and gives you some ideas.
    Andrew

  • Best practice for frequently needed config settings?

    I have a command-line tool I wrote to keep track of (primarily) everything I eat and drink in the course of the day.  Obviously, therefore, I run this program many times every day.
    The program reads a keyfile and parses the options defined therein.  It strikes me that this may be awfully inefficient to open the file every time, read it, parse options, etc., before even doing anything with command-line input.  My computer is pretty powerful so it's not actually a problem, per se, but I do always want to become a better programmer, so I'm wondering whether there's a "better" way to do this, for example some way of keeping settings available without having to read them every single time.  A daemon, maybe?  I suspect that simply defining a whole bunch of environment variables would not be a best practice.
    The program is written in Perl, but I have no objection to porting it to something else; Perl just happens to be very easy to use for handling a lot of text, as the program relies heavily on regexes.  I don't think the actual code of the thing is important to my question, but if you're curious, it's at my github.  (Keep in mind I'm strictly an amateur, so there are probably some pretty silly things in my code.)
    Thanks for any input and ideas.

    There are some ways around this, but it really depends on the type of data.
    Options I can think of are the following:
    1) read a file at every startup as you are already doing.  This is extremely common - look around at the tools you have installed, many of them have an rc file.  You can always strive to make this reading more efficient, but under most circumstances reading a file at startup is perfectly legitimate.
    2) run in the background or as a daemon which you also note.
    3) similar to #1, save the data in a file, but instead of parsing it each time save it instead as a binary.  If you're data can all be stored in some nice data structure in the code, in most languages you can just write the block of memory occuppied by that data structure to a file, then on startup you just transfer the contents of the file to a block of allocated memory.  This is quiet do-able - but for a vast majority of situations this would be a bad approach (IMHO).  The data have to be structured in such a way they will occupy one continuous memory block, and depending on the size of the data block this in itself may be impractical or impossible.  Also, you'd need a good amount of error checking or you'd simply have to "trust" that nothing could ever go wrong in your binary file.
    So, all in all, I'd say go with #1, but spend time tuning your file read/write proceedures to be efficient.  Sometimes a lexer (gnu flex) is good for this, but often times it is also overkill and a well written series of if(strncmp(...)) statements will be better*.
    Bear in mind though, this is from another amateur.  I c ode for fun - and some of my code has found use - but it is far from my day job.
    edit: *note - that is a C example, and flex library is easily used in C.  I'd be surprised if there are not perl bindings for flex, but I very rarely use perl. As an after thought, I'd be surprised if flex is even all that useful in perl, given perl's built-in regex abilites.  After-after-thought, I would not be surprised if perl itself were built on some version of flex.
    edit2: also, I doubt environment variables would be a good way to go.  That seems to require more system calls and more overhead than just reading from a config file.  Environment variables are a handy way for several programs to be able to access/change the same setting - but for a single program they don't make much sense to me.
    Last edited by Trilby (2012-07-01 15:34:43)

Maybe you are looking for