Blog

  • Flex Controlling Flash

    Preface

    This article focuses on controlling applications written Flash Player 8 and below that are loaded into Flex at runtime. If you want to read up on the various ways of doing this, I’ve written in the past how to control Flash Player 8SWF’s in Flash Player 9’s new AVM. This article specifically will talk about using Flash Player 8 content in a Flex 2 environment.

    Before you read further, I strongly suggest you beg those in charge to allow you to re-write the AS2 content in AS3 (Flex 2 or Flash CS3). If that fails, keep reading.

    Use Cases

    Here are some common use cases where one would want to load Flash content into Flex content:

    1. You have some existing Flash content that was previously written for a Flash Player before 9 (8, 7, or 6). This content could be a fully functioning application that has already proven itself by working successfully for awhile. Therefore, you’d like load it in atruntime and let it do it’s thing. There is no time, budget, and/or resources to re-write the content in AS3. An example would be a video player written for Flash Player 8/7/6 customers (those who don’t have 9).

    2. You have some content that was created by another company or 3rd party tool that you want to integrate and possibly control. This could be SWF’s generated by Captivate, Connect, Swish, or perhaps even older versions of Flash. There technically are no “source files” so you couldn’t necessarily re-write the content, or said content just couldn’t be created in Flex in the first place.

    3. You’re a Flex Developer and have no intentions of learning Flash. You’ve been ordered to load SWF’s that are not AS3 and control them.

    4. Like #3, except you can’t find any Flash Developer contractors that are available. Imagine that.

    For the record, all 3 are valiant efforts fraught with peril. Knowing this, you can re-attempt my advice to plead with management to abandon the course in folly, or grit yer teeth and git-r-done. I won’t re-iterate the problems here, you can read that in the above link. I will, however, give a quick refresher on what you can and can’t do.

    First, none of the above scenarios allow embedding. If you do not have the source FLA created in Flash, with a valid copy of the Flash authoring tool (MX, MX 2004, 8, or CS3), you have no choice but to load this stuff at runtime. If you DID have a copy, you could embed it. Embedding AS2 SWF’s, however, removes all of your code. Thus, embedding AS2 applications won’t work. You don’t have these problems with AS3.

    Second, loading AS2 / AS1 content at runtime creates a separate, special security sandbox for the SWF that’s being loaded. The DisplayObject is called AVM1Movie, and he’s an iron-clad, impenetrable black box. There is physically no way to breech it via ActionScript 3 to talk to it. You can, however, useliasons over / under the wall via ExternalInterface or LocalConnection. ExternalInterface sucks because it uses JavaScript. Every project I’ve ever done that incorporated JavaScript as a necessity added 1 more level of complexity, extended the debugging time in the project, and overall made it more challenging to make progress. Thus, while theAVM’s may be different versions, at least we’re coding in a semblance of the same language and runtime… well, more than JavaScript anyway. AS1 and he may be similar , but at least AS1 works the same in all browsers. You already have enough challenging things to worry about now that you are down this dangerous path; you don’t need another headache.

    Third, your AS3 content cannot immediately “get rid of” AS2 / AS1 content in this AVM1Movie thing. Garbage Collection will get it when it feels like it. In the AS2 / AS1 AVM, removeMovieClip for the win! It works immediately, and while the actual RAM of the used variables may not go away, all media stops (sounds, video, animation) as opposed to AS3 where you have to be explicit to do so, not just remove it from theDisplayList.

    Solution: A proxy SWF, aka proxy.swf, aka, a Flex liaison to AVM1 content.

    Why a Proxy SWF

    Since Flex 2 content (Flash Player 9, AS3 AVM+ SWF’s) cannot tell AVM1 SWF’s what to do, they use a guy on the inside, a proxy.swf, to act as agents for them in that world. The proxy.swf executes the orders that Flex issues, and these orders are communicated via LocalConnection.

    That downside is, you still need to code this proxy.swf in AS2 or AS1 and compile it for at least the Flash Player 8 or below. You don’t necessarily need Flash to do this. You could use MTASC, PHP’s Ming, or JGenerator (I think what Lazslo uses?). I haven’t gotten this to work myself, but you could also possibly use the Flex 2 SDK’s mxmlc with the “as3” compiler option set to false, and the “es” option set to true. This should generate a Flash Player 9 SWF that uses the old AVM (so… technically AS2 like code that’s compiled to AS1 bytecode using a Flash Player 9 compiler).

    …or, you could use my generic compiled example, and hope for the best.

    If you want to do it right (keeping in mind “right” here means not-so-right since we shouldn’t be using older SWF content anyway), you typically tailor a proxy.swf for the particular content you are loading. For example, if you are loading Captivate SWF’s, you build a proxy SWF that can:

    1. load in Captivate content
    2. control Captivate content by their *hidden API
    3. unload Captivate content

    * For more info on hidden API, go here, scroll to the bottom and download the big ole PDF, search for “rdinfoFrameCount” which should take you to the “Controlling Adobe Captivate projects with variables” section.

    This, as opposed to just my generic proxy that just accepts methods as strings and runs them much like JavaScript’s eval. That way, you can expose a loose API. You can’t share AS3 and AS2 interfaces, but we’re already past the point of IDE help here, so you’re really doing faith based coding at this point. Anyone whose ever used a dynamic language (as opposed to strict typing) shouldn’t have a problem with this. If you don’t code the proxySWF specifically for the content you are loading, it’s harder to debug, and basically really hard to identify which remote method invocations are failing.

    I’ve provided 2 examples at the bottom of this article. One is my generic “I’ll run what you send me” one and the other is one built specifically to control the Flash 8 Video Player. While the generic can be something you can build upon to support your content, I highly recommend you follow how the video player one is built and build the proxy.swf specifically control a specific SWF.

    How It Works

    They both work the same way.

    1. Flex SWFLoader loads an AVM1 proxy.swf
    2. proxy.swf loads the content it’s supposed to use via loadMovie / MovieClipLoader
    3. once the proxy.swf has loaded it’s content, it let’s Flex know
    4. at this point, Flex can now tell the proxy.swf to do things with the content it’s loaded

    These can sometimes breakdown. LocalConnections are by their very nature asynchronous. While you can create an instance immediately, that doesn’t mean it’s immediately available for use. For example, the AVM1 version of LocalConnection gives you a Boolean so you know if the send actually worked. If you get a true, it doesn’t mean it actually sent, just that the send operation itself “worked”. Amazingly f’ing useless. Send again? Hell… WHY NOT!?!

    The AS3 version is different. You can get a few different types of exceptions from sending messages, such as ArgumentErrors and AsyncErrors. While the docs claim that your syntax can be correct, and it could be your request is just bigger than 40k, this is a crock. Even simple strings can just fail, and then magically work later. In short, LocalConnection is flaky; you’re code should compensate. If you need ensured communication, use ExternalInterface. That, however, has it’s own can of worms.

    You do not have to use a SWFLoader. You could just a Loader, but since Flex is UIComponent based, SWFLoader is UIComponent based, so there you go.

    The proxy examples I have both use MovieClipLoader. While you could simply use loadMovie, MovieClipLoader gives you more events to understand what’s happening with your loaded content. You don’t have to write polling code yourself; instead, you have dependable events that fire. The only one you really care about is onLoadInit. When that fires, whatever SWF you are loading can now be accessed by code in an ensured fashion. This is why you wait for that to fire as opposed to onLoadComplete.

    LocalConnections

    All of this communication between Flash & Flex is done via 4 LocalConnections; 2 in Flex, 2 in Flash. LocalConnections are only 1 way. Meaning, you can only send messages or receive messages; not both. I typically use the “in_lc” and “out_lc” naming convention; feel free to make up your own. The Flex out_lc talks to the Flash in_lc. Vice versa, the Flash out_lc talks the Flex in_lc. The only thing uber confusing is that in Flex, the names are reversed. Since LocalConnections connect on a “connection name”, these 2 names need to be the same in Flash & Flex. So, in Flash I have:

    LC_IN_NAME = “_JXLFlashProxy_IN”;
    LC_OUT_NAME = “_JXLFlashProxy_OUT”;

    And in Flex, I’ll have the same thing for values, but different things for the names; just to help easy the insanity.

    public static const FLASH_LC_IN_NAME:String = “_JXLFlashProxy_IN”;
    public static const FLASH_LC_OUT_NAME:String = “_JXLFlashProxy_OUT”;

    The only difference is in Flex, you use the OUT name for your Flex “in” connection. Since Flash is sending messages out on the OUT connection, Flex needs its IN connection listening to the “Flash OUT” connection name. The reverse holds true for Flex sending messages. He’ll send them on Flash’s IN connection name.

    To reiterate, these messages are asynchronous. They don’t arrive immediately, and you cannot return values. You can treat it like events, where the LocalConnection in Flash can send a message back to Flex with data, but unlike events, you can’t depend on this; some messages just don’t make it.

    Dynamic Flash

    If you are not familiar with Flash, you’ll notice that both AVM1 examples just dig right into the SWF they are loading. This is because there is no runtime strong-typing in pre-Flash Player 9. For example, if you look at the video_player2.fla, you’ll notice some methods on the main timeline. Flex asks the proxy.swf to call those methods since he can’t. Like a kingpin asking a thug to get his hands dirty. I can access those methods as if they were public class methods… even dynamically by concatenating strings together in Flash Player 8 and below. This is where a proxy.swf shines in that since it’s made in dynamic Flash land, it can play by dynamic Flash rules. This is important because sometimes you’ll be loading SWF’s that you don’t have code control over, and need to jury rig them to do things they weren’t originally intended to do.

    Keep in mind a proxy.swf can do more than just dynamically call methods and set properties on a load SWF application. It can also affect the nature of that application. Since you are still in a prototype based language, an object’s prototype property is writable. Thus, even if you don’t have the source, and don’t feel like using aSWF decompiler to get some form of source, you can overwrite prototype objects that you introspect to force the SWF to do things you need.

    …you know, in writing all of that, I’d much rather use a proxy.swf with ExternalInterface. As much as I hate JavaScript, it was pretty easy to break LocalConnection. Maybe next weekend…

    Source Code

    Video Player Flex Example – Example | View Source | ZIP

    Generic Flex Example – Example | View Source | ZIP

  • E4X XML Binding & CDATA

    The benefit with using international standards when creating software is that you can blame to stupid design decisions on “an international team of brilliant computer scientists”. That way, if someone tries to body-check you on the pathetic implementation, you can defer to aforementioned governing body. That way, you’re calling an international standards body a bunch of crackheads, thus making you look like a crackhead. Who in their right mind would attempt to insult a group of talented individuals from around the globe brought together for the specific purpose to collaborate on creating a new programming API?

    Me. I call it like I see it and it’s crap; specifically, CDATA handling in E4X.

    For background, CDATA is a way to put “character data” which is basically text that could have funky characters in it like HTML. Since XML is made up of HTML like syntax, you want to make sure that you can put HTML into XML, and not have itscrew up when parsed. Enter the CDATA tag, a special tag that tells the parser (whoever is converting the XML text into something useful, like Flash or Flex for example), to ignore parsing anything inside of it. Kind of like the “pre” and “code” tags in HTML.

    Putting these special tags into E4X XML is impossible when combined with binding. Binding is an extremely useful way of creating dynamic XML from variables without having to construct it manually. Since XML is a first class citizen in AS3, you can basically copy and paste real XML into your ActionScript, and set it to a variable.

    Even cooler, though, is the binding; sort of like Flex’ databinding, except it works inside of the XML nodes. So, if you are building Factory classes for example that create XML request packets to send to somewebservice, you can make a function that takes some parameters to customize the request, and return the XML, like so:

    function getLoginRequest ( username : String, password : String ) : XML
    {
        var request:XML = <request>
                                <login>
                                    <username>{username}</username>
                                    <password>{password}</password>
                                </login>
                            </request>;
        return request;
    }
    var request:XML = getLoginRequest("Jesse", "moogoo123");

    Working with a talented PHP dev at work named Nick, and he requires me to send a URL in my request to one of the services. We don’t make heavy use of attributes, which you can actually get away with a lot of HTML character data without XML getting mad, even in the old DOM way.

    The URL, however, kept getting URL encoded. The URL was ALREADY URL encoded because it had some parameters on it that the server would use later. However, it seems E4X does automatic URL encoding (akaencodeURIComponent or it’s ilk) on the text you throw into nodes.

    So, I tried Just putting a CDATA tag instead:

    var theURL:String = "http://some.com?var=someval&foo=bar";
    <the_url><![CDATA[{theURL}]]></the_url>

    …however, bindings don’t work in CDATA tags like that. Since the CDATA is doing what it’s told, and telling the XML parser in ActionScript to ignore the inner contents, this includes the binding. Shoot!

    So, I tried creating it as a String:

    var s:String = "<![CDATA[" + theURL + "]]>";
    <the_url>{s}</the_url>

    …but then it URL encodes the URL again!!!

    <the_url><![CDATA[http://some.com?var=someval&amp;foo=bar]]></the_url>

    Son of a…

    I then tried various other ways of doing the same thing, all to no avail. In DOM, we had XML.ignoreWhite, which basically told the parser to ignore whitespace. There doesn’t seem to be the same sort of setting for E4X to turn of automatic encoding. Furthermore, you can treat the CDATA node as just a normal String, unlike the old DOM which was a tad more explicit like node.firstChild vs. node.firstChild.firstChild (or was it nodeValue… forget).

    Anyway, DAMMIT!

    Michael Schmalle had a fix. You CAN bind to functions as well. It’ll do an automatic invoke (just like a getter for example), and you can return whatever you want. So, doing this:

    function cdata(theURL:String):XML
    {
        var x:XML = new XML("<![CDATA[" + theURL "]]>");
        return x;
    }
    <the_url>{cdata("http://some.com?var=someval&foo=bar")}</the_url>

    Flexcoders for the win.

    I’ve gotten used to namespaces. They make sense; while verbose code, at least verbose pays off in AS3 with speed at runtime.

    CDATA handling, however, is an f’ing joke. If it DOES handle it well, then the docs are an f’ing joke. Neither of which is funny. No one cares, though, because I gotta fix and Nick could remove his Base64 decoding hack he put in for me as a temporary band-aid.

  • Flex with REST Same Name Parameters, and SSL

    Have a plane to catch, so figured if I blog when I have no time, I’d be brief for once in my life. Ready? Go.

    Currently in Cali, awaiting for my flight to board back hom to ATL. Cali is 20 degrees colder than ATL; lame. 72 F (22 C) back to 91 F (32 C) will be a welcome change. I was here on-site with a client doing some consulting for my current contracting client. Confused yet? Don’t be, it’s fun. Figured I’d document the Flex lessons I learned while in the trenches the past 2 weeks.

    First up, what do you do when a server-side developer gives you a REST API that has support for multiple parameters with each one have the same name? HTTPService won’t work as you think. HTTPService in a nutshell does a POST to some URL that supports parameters being sent to it in URL encoded variables. So, this:

    var o = {};
    o.name = “value”;
    o.cheese = “muffin”;
    o.skillz = “mad”;

    becomes:

    http://www.cow.com/some.php?name=value&cheese=muffin&skillz=mad

    HTTPService has 2 ways to give it stuff; either set it’s request property before sending or pass it in the send function. However, if a WebSevice accepts this:

    param=val1&param=foo&param=bar

    Well… you’re kind of screwed. There is only 1 param…

    var o = {};
    o.param = “uno”;
    o.param = “dos”; // overwrites uno
    o.param = “tres”; // overwrites dos… all are same param variable

    I tried my best to hack the IMessage object that’s associated with an HTTPService AsyncToken (mx.messaging.messages.HTTPServiceMessage I think), but no go. What to do? Uber l33t h@x of course!

    1. At beginning of Cairngorm Delegate, store service URL property in member variable.
    2. append your parameters manually the the server.url
    3. var token = service.send();
    4. in result / fault handles, set the service.url back to what it was

    Works. Potential problem? If someone ELSE attempts to use that service, it’ll have that URL stored with it, with the URL encoded variables included. If your HTTPService is only ever used once, you’re good to go.

    Second, SSL. SSL is not hard. I remember keeping that Ted Patrick SSL Flash / Flex entry bookmarked for the day a client would require Flash / Flex & SSL. I remember reading horror stories.

    Those didn’t happen to me, though. I think in hindsight, every one’s problem was SWF security sandbox problems and NOT SSL problems. I remember reading about IE caching things, but either way, the ONLY thing that didn’t work was IE 7 on Vista because our security cert didn’t match up 100% with the real URL (we’re testing,hehe). Mac with Safari & Firefox, and PC XP with IE 6, IE 7, and Firefox all worked.

    We’re not just talking about using HTTPS here for secure longins, we’re talking about:
    – EVERY single request is HTTPS
    – this includes file uploads
    – the SWF is on the client’s website, but loaded from our webserver

    That last part is the kicker. I learned that crossdomain.xml files have to explicitly allow ports, in this case 443. Dope!

    Anyway, really rad to learn that if I ever develop widgets professionally, I can get SSL to work on said widget no matter where it is. I think the rule of embedding it with JavaScript with a relative path applies (like UFO or SWFObject); the SWF’ll think it’s loaded via HTTP, and go “Oh noes!!!”. Hardcode that mofo to https://blahblahblah.

    Speaking of which, anyone know of any site like Akamai that supports SSL? Interested to hear how they handle it.

    Finally, some cool links. talks about what I already know. Disagree about his points with regards to “if you don’t blog, you won’t get a good gig compared to someone who does” but the rest I do. If Expose and you raced, and you had this table as your computer screen, who wins? Finally, a video of Steve Jobs and Bill Gates getting interviewed together. Haven’t watched it myself but how can it not be cool?

  • Cairngorm Command Flaws and What You Can Do About Them

    From Day 1 I hated how Cairngorm Commands / Delegates didn’t give a status to what they were doing. Since Flex‘ primary purpose is a Rich GUI, and there isn’t a built in way to get status on Commands. For example, the flash.net.FileReference object will give you a progress event. This gives you the ability to show the actual progress of the upload in a progress bar. While most Commands are simple request / responses, sometimes you’ll call many of these in a row, with different ones at different times in the case of editing wizards.

    Even more important, however, is the flow of this logic. Some Commands contain logic that can be re-used elsewhere. For example, a GetPerson Command that get’s a specific person from a database by ID. There can be many other scenarios where you need to get a specific person from the database where you wish to store a local reference to it (for an EditPerson form for example), or you are just querying the data for some other operation. This still poses a problem for other Commands, however. They can’t re-use the Command in the Cairngorm way, but rather the Delegate way. Meaning, a Delegate usually takes in an mx.rpc.Responder. Therefore, you can call a method on a Delegate, and get a useful response in a result handler when it’s done, and an error response in a fault handler. You can’t do that with Commands. Commands are run only by the Controller, and have no callback support built in.

    While a Delegate, assuming one exists for the specific Command in the first place, is a viable way of re-using functionality, the application logic usually happens in the Commands, not the Delegates. The Delegates are responsible for merely getting the data, and parsing for use by the application. The Commands are the ones who do useful stuff with it like stick on the ModelLocator, or update your data model as appropriate. That valuable, and specific application logic is what I’m talking about here. Written in an encapsulated form, it is ripe for re-use. Yet, you can’t.

    Therefore, the only official way of sequencing Commands is using the SequenceCommand which basically locks you into a specific order, puts too much knowledge into a Command, and risks making them state-full. Meaning, by default you are locked to a specific order; the order in which you coded the Commands to call each other. The potential exists for a Command to “know” it was called by something else, thus forming a potential dependency. Dependencies bad. Third, if you know this, you may be tempted to put some conditional logic in there to help adjust for this and say “If I was called by the GetPerson Command, then I need to do this… otherwise, I’ll just do this.” Commands are use cases, and shouldn’t be determining the “way” they run the use case. If I ask you to SaveTheData, just save it. The Event that gets passed into the execute function tells the Command all it needs to know. While some would argue that the alternative Cairngorm where you have Many Events for every 1 Command as opposed to the default which is 1 to 1 allows this scenario to work well. While very true, it doesn’t scale well. Meaning, while having 1 LoginCommand capable of doing the work for a LoginEvent, ForgotPasswordEvent and ChangePassword event is very possible just by adding a switch statement for the event’s type in the execute function, your classes get very big, and less flexible. Yes, you do end up with more classes, but that’s what folders are for. Furthermore, there is nothing wrong with a bunch of classes that have less than 100 lines in them. Compare this with a few classes that have a thousand each. This is why a lot of people like Ruby on Rails; does a lot with few lines of code.

    Remember, we’re running client code here, not server-side. Our scalability needs are for code maintenance not performance. So, in this case, less code is better regardless of the performance implications.

    Even worse, you run into scenarios with the above where you have the urge to make your Commands state-full, meaning, they “remember” their state. That further makes your Commands less re-usable. Now to use a Command, you as the invoker have to know how the Command will use the Event class you choose, who it may call next, and what state it may already have. As if programming wasn’t hard enough. You shouldn’t have to know all of that stuff. Just dispatch an event, and have faith your use case will get resolved.

    How to solve these issues? If you were using Joe’s Controller, you could just add an event listener, make your call, and get an event when it was done for the asynchronous operations. For the synchronous ones, you could just return a result. Taken a step further, you could also return a token instead. For example, if the Controller were just an instance, the event model would work well. As soon as you handled the the event, the Controller instance would go out of scope, and the Garbage Collector in Flash Player would clean it up. However, Controllers are Singletons, so that won’t work. This means the user of the Controller is now responsible to “remember” to do a removeEventListener to ensure it doesn’t get events later it doesn’t care about. Kind of like the space shuttle docking with the space station. When it’s done, it first un-docks. That’s lame, though. It makes it a pain to deal with.

    The third option is to do what HTTPService and friends do using the token pattern. Since HTTPServices can either be used as 1 time instances or act like a Singleton (only 1 instance instantiated 1 time in the Services.mxml), it needs to support both ways of working. As such, all calls create their own instances of the call and return it. In this case, they’ll make a call, and associate a token with it. They’ll return this token to the caller. When the call comes back from the server, the HTTPService knows which token it is for, and so does the one who called it since he has a unique token for it. You can treat these tokens as instances. The only minor downside to this is when you are using these classes like HTTPService as instances, it takes a few more lines of code just to make a call. This is because it is assumed you’ll usually be using only 1 instance, but the class creators don’t want to lock you into an implementation, so give you the option to do both. Bottom line, the Token pattern is really for the developer to be able to tell the difference between multiple calls to the same service by comparing the token you get when making the call to the token you receive from the result handler’s event.

    …in Cairngorm’s case, he doesn’t have that option. You dispatch an event and that’s the last you hear of the call. Years ago, the suggestion was to simply set a ModelLocator variable as a state variable, and change it’s value when the Command was done. The first problem with this is that it only works if you only ever call the Command once. Since Commands are created as stateless instances, you could have a scenario where many are running. One variable cannot work for keeping state of all Commands. Secondly, this doesn’t scale because you then have state variables. View’s in Flex 2 have a great way of representing their own state and don’t need to offload that baggage to the Model. While the View can react to a change in the Model such as databinding, for GUI development, you need more than just a global variable. You need callback support.

    I developed some extensions to Cairngorm to support this as have others. Grant Davies and I originally did this for back in the Flash days, but with a different approach. We removed the need for Events, and just gave Controller the ability to launch Commands via method calls. We’d pass in parameters with the first 3 being scope, result callback function, and fault callback function. This allows any View, anywhere, to launch a use case AND have a result callback when the Command is done. Cairngorm & default ARP can only do the first part, not the latter.

    This changes the game, though for a lot of people’s perceptions. This means that the View in some cases is acting like a Controller. This is hard for a lot of traditional, non-Flex / Flash devs to understand. Traditionally non-GUI code handles this. However, a lot of people just assume that in Cairngorm’s case this means the Commands which leads to some of the problems mentioned above. This lead to the use of ViewLocator, a Singleton class that can access any View that has registered itself via a String. This allowed Commands the “formal” ability to access a View’s methods whenever it felt the need. The only justification I’ve have for this disgusting class was in a discussion over IM with Spike Milligan. It is in the case of a base Delegate detecting an expiring of a user’s login. You need some way to make the whoever your main view is to spawn a Login View in a PopUpManager. Another way is to have your main view add an event listener to the CairngormEventDispatcher for a “PromptLoginEvent”.

    A lot of Views in Flex case aren’t really View’s at all. SystemManager for example merely manages how the application is setup to actually show Views. Application.mxml is the main View, but typically he only has 2 children, the CSS style sheet you are linking in and Darron Schall‘s “MainView”… aka, your app.

    three_flex_views.png

    Even more granular, now that event bubbling is built into the Flash Player, we can encourage the “higher views have higher concerns” paradigm. Meaning, the higher the View is in the DisplayList, the more important it is. For example, Application.mxml is pretty damn important. Without him, you have no Flex app. MainView is the 2nd most important; he instantiates Cairngorm and starts your main application up. Without him, you just see the loading bar and resulting blue gradient. In an EditPersonWizard, he manages child views which in turn manage specific Person properties. An important key here to the whole thing is that they listen to their parent. If the parent, the EditPersonWizard, says next step, they disappear. The parent manages the children in the wizard, sets their data, and keeps a track of their changes. When the choreography is done, you’ve “Edited your person using the Edit Person Wizard successfully. Have a nice day!”. In effect, the EditPersonWizard is a controller. The same can be said for MainView. The same can be said for Application. They don’t just instantiate Views; they control them.

    One thing you should strive for is to NOT put Cairngorm specific event dispatching in your View’s. You should treat them as encapsulated components that you can reuse. Rule of thumb: If you can put a Cairngorm event to be dispatched in a parent instead of the current View, do it. With Flex 2, it is now easier to do this by either dispatching an even up to the parent, or just bubbling it up even higher than that. You should define the events in the MXML metadata, since a parent should know which events its children will dispatch, even if it won’t actually use them. This is very valid, btw; I don’t use a Button’s mouseDown or render event, but I commonly use its click event. Either way, all 3 are strongly-typed. You should make your Views strongly typed as well, even with the events.

    In effect, this allows your child views to dispatch events up the DisplayList and those higher up the chain who need to know get what the need to know. For example, a Button inside Step3 inside of EditPersonWizard doesn’t need to be reporting that the user clicked him to MainView.mxml. Step3 knows how to manage his subordinates and take the appropriate action. He’ll inform his parent, EditPersonWizard, of any changes that are important.

    What if Step3 needs to get a person from the database, however? Could you not just put a Cairngorm event dispatch right there in Step3? Of course! If you are in a hurry, go for it. Deadlines are deadlines. Should you? No. You couldn’t re-use this View elsewhere without dragging all of your Cairngorm code with it to work. Instead, you could build in a setter for the EditPersonWizard that was specifically put in place some MainView could then set it. But how does MainView.mxml know when to get the person? Does it need it immediately, or is it optional? In this case, we’ll Delegate the responsibility to Step3. Support is built into EditPersonWizard, but nothing is implied or demanded. Step3, when needed, can bubble the event up. EditPersonWizard can then do absolutely nothing as the event passes by. MainView can then catch this event (it’s defined in the EditPersonWizard’s metadata tag remember, so we have strong-typing in MXML here), and do the normal Cairngorm getting of data routine. Even without callback support, the data is set on the ModelLocator via the Command, and since it’ll probably be bound in MainView like , it’ll then propagate that data down to Step3. You’re effectively delegating authority just like real management does.

    You can see if you build View’s this way 4 things happen, 2 of which are good. First, you’re views are re-usable since they don’t have Cairngorm dependencies. So, you can re-use in the same application even with different data. Second, you don’t have to bind a lot of View’s to ModelLocator. Instead, they are given their data to them by their parents, again making your View’s more flexible. Third, you write more code in your View’s to support data in children. While this is more code, it’s good code in my view. Still, more code isn’t necessarily good, but better more code for the sake of encapsulation. Fourth, your higher level views spend a LOT of time getting data for people. If this is MainView.mxml for example, who has very little Views to handle, this is a great thing. For one thing, ALL Cairngorm use cases are dispatch from (hopefully, not always the case) 1 spot. Just like Commands are great in that you know for a fact they are usually the ONLY ones who set data on ModelLocator, you can be sure that the only one handling main application control logic is in MainView.

    The downside is this can be a lot of code, even for smaller apps. This is why a lot of programmers feel they need to put this stuff in Commands since at first glance, they appear related. They aren’t, though. The View’s are dictating what data they need since they are best suited at this. Things like lazy loading happen at the View’s discretion for example vs. the Controller. Further, the Views are the ones passing data up, whether packaged in an event object, or exposed view public getters. The parents of those Views as well as MainView may have context about that data that Commands may not know. In effect, you shielded the Commands from all of that View logic… thus reducing their code size. That’s a good thing! Views should be managing Views. Views can act like Controllers for other Views. That’s just the nature of GUI development whether composition or inheritance.

    The fatal flaw in this scenario is that MainView is crippled in this scenario in getting back to the View’s with their needed data or progress events. If you ask for time off from your manager, but their boss never responds to emails, you’ll never know if you can take those days off you need. This is the main problem I had with ARP, and the same problem I have with Cairngorm. With Cairngorm, I modified CairngormEvents to store callback functions. “Call this when you’re done”. This callback is then called from the Command “when it’s done”. This could be immediatley or after a Delegate returns from the server… whatever, whenever. Bottom line, a View can get a response when a use case is done. In this case, MainView can then pass the data down to EditPersonWizard, who will then pass it to Step3. If the Command just set it on ModelLocator, MainView doesn’t have to do anything in this case. But, if you were saving your changes, for example, and EditPersonWizard was disabled while the save happens, MainView can enable the form again once the save has successfully completed.

    In effect, this makes MainView a very effective View controller. For scalability purposes, you make a few MainViews who manage their section of the app.

    One of these days I’ll explain the technicalities behind using Callbacks; strongly typed responses that Delegates return to Commands, who in turn can return to Views. Views can use them just like they use ValueObjects, and get only the info that a Command allows it to have. ResultEvent is too generic, not strongly-typed, and View’s have no clue what they are supposed to do with it. Furthermore, it’s a code dependency risk too. That’s another blog entry…