Category: ActionScript

  • Bucket Brigade Pattern is not Dead in AS3

    I’d like to know how others are handling the fact that Event bubbling only works with classes that extend GUI objects (aka, DisplayObject).

    If you already know how event bubbling works, you can skip to my problem.

    Background on Event Bubbling

    Event bubbling is dope. It allows you to have a deeply nested MovieClip (View) dispatch an event and “let you know it did something relevant”. The “let you know” part is accomplished by the bubbling being set to true for the dispatched event, and the “relevant” part is making the assumption you’ve listened for the event type its dispatching.

    (more…)

  • Gaia Arguments, Real World Bridge Pattern, and gaia_internal

    The Gaia Beta was released today by a friend of mine, Steven Sacks. Gaia is a Flash framework created for Flash Designers & Developers who create Flash sites. The reason this is an important is that it now supports ActionScript 3 and Flash CS3.

    Discussions

    I must of racked up at least $500 in cell phone / mobile bills talking to Steven about Gaia over the phone over the past few months (he’s in Los Angeles, I’m in Atlanta). This doesn’t include numerous emails and IM’s. We’ll argue about implementation details, coding styles, and design pattern implementations. Sometimes their just discussions about details because we agree and are on the same page. The arguments about terminology and Flash authoring techniques are usually one sided; Steven stands his ground, has chosen pretty appropriate industry lingo, and knows his audience way better than I do.

    My job isn’t to congratulate him on the immense amount of work he’s done on the AS3 version, on porting the new ideas gained in AS3 development BACK into AS2, or for just the good execution of his passion. My job is to be his friend. That means to question everything to ensure he’s thought thoroughly about something, to be devils advocate, and generally be a dick to see if he cracks. If he does crack, it’s a weakness exposed, and we then have to discuss about who’s opinion on fixing it is better.

    This doesn’t happen with everything, only small parts of Gaia that he asks for feedback on. The rest I have confidence he already got right… although, I did manage to write 24 TODO’s/FIXME’s for 3 classes he wanted my feedback on. F$@#ker only agreed with like 2… or at least, he only openly admitted 2 were decent. I’m sure if I did the whole framework, I’d have more, although, I might have less once I then understand most of the design decisions :: shrugs ::. Doesn’t mean Steven would agree; it’s his framework and he’s a good Flash Developer. With his understanding of other Flash Designers & Dev’s and how they work, he ultimately knows best.

    Solving the “no more _global” Problem

    One part Steven DID let me actually help a lot on was the global Gaia API. In Flash Player 8 and below, this Singleton existed on a namespace called “_global”. This was a dynamic object you could put anything you wanted on and all code everywhere, including dynamically loaded SWF’s, could access. Aka, the perfect place for the Gaia API Singleton. Naturally, we both were like… crap, what the heck do we do since there is no _global in AS3. Damn Java developers can do DIAF. Someone get that Python creator guy’s number and tell him that Macromedia would like to re-consider their offer back in Flash 5 instead of going with ECMA… oh wait… Macromedia is no more… dammit!

    It just so happens, Steven remembered reading my blog entry with the proposed solution for Flash CS3 not having an exclude.xml option. The server architect and long time Java dev at my work, John Howard, suggested the Bridge pattern idea initially, explaining that interfaces are smaller than actual class implementations in file size. Steven and I discussed the Bridge pattern way I suggested, using internal classes in an SWC sneakily injected into people’s Libraries, and another solution proposed by one of my readers, Sanders, in the comments. The Bridge pattern seemed best, but we were concerned about file size because it was an un-tested theory. As you can see, this turned out to be a good theory; 1.3k == f’ing dope!

    When I went back and re-read my blog post I realized I didn’t really explain how the Bridge pattern works in Flash Developer lingo. As my blog reader audience has accumulated Java & C++ devs just getting into Flex, I’ve tried to use lingo they’d jive with. So, let me re-hash what the Bridge pattern attempts to solve in 1 2 3 4 sentences 1 paragraph.

    You cannot exclude classes in Flash CS3 using exclude.xml like you could in Flash MX 2004 using AS2. Therefore, if you re-use classes, say “Gaia.api.goto” in other FLA’s that will later be loaded in, you’re duplicating classes in many SWF’s, greatly increasing the file size of your entire site. Instead, we just created Gaia to be a shell that makes calls an object “we’ll set in the parent SWF”. This Gaia shell class compiles to 1.3k vs. the 6 to 12k the implementation would of normally taken. That’s 10k (probably more) savings per SWF.

    These savings make HUGE differences on enterprise size Flash sites like Ford Vehicles and Disney; basically any huge Flash portal that gets one million+ visitors a day. Akamai or other CDN‘s aren’t exactly cheap. The 10k you save per SWF could be $10,000 in bandwidth costs per month. But screw the bandwidth costs, it’s all about the user experience, baby! Fast for the win.

    The gaia_internal namespace

    The down side was I KNEW we’d have to expose at least 1 public variable on the Gaia Singleton. We don’t want people setting things on the Gaia api class they aren’t supposed to; whether on purpose or by accident (accidental h@xn04?). So, I copied what the Flex SDK does. They use this thing called “mx_internal”. It’s a namespace the Flex team created for the same situation: You want to expose a public property, but you don’t want other people messing with it.

    You can’t use private because it’s not accessible by other classes. You can’t use protected because you have to extend the class. You can’t use public because that implies its ok to touch… like certain outfits certain genders wear… and in the same vein, that doesn’t really mean you CAN touch! In that scenario, it’s a wedding band. In the ActionScript scenario, it’s using a specifically named namespace you create your self. I suggested gaia_internal. That way, only Steven can use that namespace and thus set those properties. If other people do it, they’re either really smart, or crackheads. For the latter, it makes it easier to call someone out on doing something un-supported if they are actively using the gaia_internal namespace in their code.

    It ALSO makes it easier to change implementation details in the future if Steven so chooses. Like all things in Flash, even AS3, things will be custom created for certain projects. This could include changes or extensions to the Gaia framework itself. You should encourage this instead of be against it. Therefore, keeping weird internal things in a specific namespace helps, at least a little, ensure existing projects won’t have to worry too much about changes & improvements in future versions of Gaia.

    Future Solution: Using Flex’ compc

    Yes, Sanders, your solution is technically superior. As others have told you, however, it is too complicated. Flash Developers thrive on getting cool stuff done quickly. While I’m sure some Linux afficiando, command line pro, Emacs weilding zealot will argue that he can run your solution faster than I can hit Control + Enter, most Flash Devs don’t care.

    We all agree the Gaia api should be 1 class; not 3. The whole point of the Bridge pattern is to support new implementations. I highly doubt Steven will ever create a new implementation of Gaia; we just followed the pattern to save filesize.

    Therefore, what you need to do to both win the hearts of millions of Flash designer & developers everywhere as well as fix a flaw in Flash CS3 is to write a JSFL script that does your solution; and then have a way to map your JSFL script as a keyboard shortcut (this part is easy; its built into Flash). The golden rule in Flash is you should be able to “Test Movie” and see it work. It’s the same thing as checking in code that compiles into a Subversion repository. If you nail that, you’re golden and the Bridge pattern way will then become a nightmare of the past we can all forget.

    If you need help writing JSFL, let me know; my skills are rusty but I can re-learn pretty quick. The goals are:

    1. Get a JSFL script to compile as normal so you can see a movie work via Control + Enter “Test Movie”
    2. Get a JSFL script to run your magic so the classes you don’t want compiled in (aka Gaia, PageAsset, etc.); you can then map this to like Control + Alt + Enter (or whatever)

    Conclusions

    If you’re a Flash Developer who builds Flash sites, go check out Gaia. If you’re using a ton of loaded SWF’s in your site, go check out my original entry as I now have proof the theory works. If you’re Sanders, GET TO WORK! AS3 Flash Site is about to die… needs Sanders’ bandwidth reduction, badly!!!

  • When You Hit a Design Brick Wall in Flex…

    …code it your bloody self. But first, weigh the consequences. I’m referring specifically to when you have a design that you are trying desperately to shoe-horn into the Flex components. Key phrase here being “shoe-horn”, meaning it doesn’t fit quite right.

    A lot of designs can have specific elements that can be extremely challenging to implement into Flex. Challenging in this case means taking a LOT of time. If you are getting paid to learn on your employer’s dime, as you were. If, however, you just want to get stuff done, you can extend the appropriate Flex framework base class and code it yourself. There comes a turning point when the time spent trying to successfully integrate a design is more than the time it would of taken you to whip up a workable solution by coding a similar component yourself. The con is that your agile approach (least amount of work to hit the goal) may not scale and you’ll be constantly “upgrading features” on your custom component. The challenge here is to weigh the risks of both.

    Preface

    I’ve been using Flex 3 Beta for awhile and only recently got to dig into the new designer friendly features they’ve added. Frankly, the faster mxmlc it has now would of kept me happy for at least 8 months, hehe. Seriously, though, the new CSS previews, the faster and slightly more accurate Design View are really great.

    The Flex SDK itself, however, still is relatively the same in API and design integration. They’ve made massive improvements under the covers, but nothing drastic in work flow. While we’d all love low-level generated MXML that Thermo makes, or the uber-abstraction Flex 4 might give, what we have now is what we have now. Bottom line, if you’re doing ANY design in Flex right now, you’ll want to be using Flex 3 instead of 2.

    I’d say 90% of the apps out there for Flex, the current Flex 2 and Flex 3 SDK component set is spot on for. More than half of those probably need little to no tweaking to the default styling. This is based on my consulting experience, as well studying what existing .NET and J2EE implementations look like, and thus set expectations for.

    The consumer applications you see blogged by Ryan Stewart and on Techcrunch are dope looking, but I’d still argue a lot of consumer facing Flash Player content right now is still created in Flash, mainly because of the designer’s heavier role in consumer oriented content. That’ll change as time goes on, specifically in the application realm, never for the branded website.

    Examples of Brick Walls

    Let me point out some examples.

    Did you know that the TabBar & TabNavigator don’t support negative padding? They do, but not to the desired effect. The default horizontalGap property is actually -1 so the borders overlap. However, any more than that, and the 3D effect is lost.

    Tab’s give the illusion of depth to indicate which one is currently selected. They sometimes also have a bottom that has the same color of the form below it, making it even more apparent that is the state you are currently viewing. They do this by appearing “in front of” the others.

    tabs.gif

    You’ll notice some interfaces have tighter spacing on the tabs making them scrunched together. This effect gives you a lot more room for more tabs. It also accentuates the fact that the tabs have depth. The Firefox web browser’s tabs are nice and snug next to each other with only a 2 pixel gap.

    tabs_02.gif

    IE 7 takes this a step further and changes both size and height of the selected tab to show prominence.

    tabs_03.gif

    If, however, you want to show negative depth like this comp shows:

    tabs_04.gif

    …it won’t work. In Flex, it looks like this with a horizontalGap of -4:

    tabs_05.gif

    Whoops, the “Tres” is up-staging “Dos”! He IS on top of “Uno” however.

    Why does the TabNavigator, and thus TabBar work this way? You have to dig into the code of their base classes to find out. There are a couple reasons why this is, but the quick answer is that selectedIndex is hard-coded to depth. That means that it uses the index of the child keeping track of depth. If ToggleButtonBar kept an internal reference to the child instead of using depth and selectedIndex as a 1 to 1 relationship, you could change the depths of things to be “in front of other things” irrespective of selectedIndex’ value.

    No, you can’t hi-jack the depth; that REALLY screws things up and confuses the heck out of the poor thing… visually anyway.

    // TabBar's itemClick handler
    protected function onItemClick(event:ItemClickEvent):void
    {
            var tab:UIComponent = event.relatedObject as UIComponent;
            var index:int = tabs.getChildIndex(tab);
            tabs.setChildIndex(tab, 0); // nope
            tabs.setChildIndex(tab, tabs.numChildren - 1); // nice try...
    }

    Maybe this’ll be a footnote in Doug’s book, hopefully with more curse words at things that blow.

    So, you’re condemned to greater than or equal to -1 horizontal-gap style for TabBar & TabNavigator… or ARE you? This is Flash Player, ladies and gents, and you’re a coder (or hybrid). In 4 hours (tell the client 12 just in case) one could whip together a wrapper class that instantiates mx.controls.tabBarClasses.Tab, keeps track of a selectedIndex, and positions them to the design.

    Cons? Tons. This still won’t fix TabNavigator, just TabBar. Furthermore, you’ll have toggle a ViewStack’s selectedIndex manually, thus spilling out un-ecapsulated code into the Mediator that hosts both controls. Those AND all the other things that you’re giving up with layout and events that the Flex TabBar already provides. Worth the cost? For a prototype, hell yes. For a production app, no way. Ask the designer to give you a re-designed TabBar without a negative depth. Most designers I know will be totally cool with that and save you days of coding & debugging, ecspecially when they see the look of desperation on your face. I find rubbing your hand through your hair, a big sigh, and a general look of desperate exasperation really help put on a good show. Acting like the designer is Obi Wan, and you’re Leia generally ALWAYS works.

    Example 2, Icon and Label Placement in a Button

    The Button control in Flex has 2 properties that allow you to decorate it with internal design funk. One is called “label”; it allows you to set dynamic text on top of the button. The other is called “icon”; it allows you to set an image for the Button. By default, the icon sits to the left side of the Button, and the label sits to the right of the icon. The problem, however, is that the icon that “follows” the text by 2 pixels. This value can be adjusted by setting the horizontal-gap style. However, if you want to implement this design:

    tools_01.gif

    It’ll instead look like this:

    tools_02.gif

    This one isn’t so bad. You can actually just export the up, over, down, and selected states as flattened bitmaps from Fireworks and you’re good to go. Cons? If you’re font changes from anything but Black Arial 12, you’ll have to re-export your images from Fireworks, and re-compile your Flex app (loading at runtime is a cool optimization later, but you need to embed to quickly build your app). Furthermore, all the styles in Flex for your Button are pretty much worthless; this includes if someone uses the Button selector in CSS; your Button will ignore most.

    …or you could create your own Button. One that handles it’s own selection states, creates an image where you want, and a label where you want. Coding the styles, though, OVER, is a lot of work.

    Example 3, Custom Panel

    The Panel and TitleWindow components in Flex are really great to work with. They provide a nice, visual container with highly defined borders that gives the user something to focus on; functionality within the Panel is implied to be grouped and thus related. Since it’s a Flex container, you can just put whatever you want into it, and it’ll handle where it goes based on the layout property.

    A lot of Flex devs will relegate these things into some MDI interface. They’ll make the Panels draggable, add custom buttons to the title bar’s, and make them re-sizable. All are really dope.

    The problem, though, is that getting your custom border to be seemless and yet still retain all the functionality of the Panel is a LOT of work. You have basically 2 options.

    The first is to extend it. The Panel has 2 main features you need to know about to make the most of your new class. The first is the rawChildren that a lot of Containers have. This is where the internal stuff goes. The regular children that developers add go in the regular content sprite, “contentPane”. You may want to add stuff to rawChildren; where all the things that make up some of the Panel’s chrome. The rawChildren is not acessed by DisplayObject methods like getChildAt, and addChild; they proxy usually to contentPane. The rawChildren is where the fun stuff happens.

    You can also add stuff to it as well. For adding custom buttons to the Panel, for example, you’d add them to the “titleBar”. The titleBar is a UIComponent added to the Panel’s rawChildren. That is the “thing” up top that houses the close button, title, and status text amongst other things. This is the easy part. Even the border metrics, the measurement one does to ensure that your border fits around the contents, are challenging but definately do-able in 12 lines of code.

    …the title background, however, is where things start to go downhill. Chrome in the rawChildren is ABOVE all content. This really really sucks. If you’re doing programmatic skinning, this creates chrome on top of your controls; aka the close button and others. You don’t have to, could use scale 9 images, but you’d still have the same problem. This means no clicks get through to the buttons and stuff appears “on top of” it/them.

    Solution? Override the mx_internal namespace function called “createContentPane”. The one that is in Flex 2’s Container class on line 4608 (4632 in Flex 3 Beta … um… beta something) clearly states the location of your chrome. You’re screwed unless you override it. You can follow my original foray into this horrible, malaria infested jungle, originally forged by Michael Schmalle.

    What’s wrong with overriding it? Well, let’s get a quick eduction on what Adobe officially supports in the Flex SDK, and what they don’t. First, if it’s public or protected, you’re good to go. If it’s in the mx_internal namespace, or it’s private, they do not. Their reasons for this is that they can change the functionality under the hood, yet still expose the same API in future fixes/updates/verions of Flex that won’t break your app. Additionally, there could be other things released in the future that use the Flex SDK’s API but wouldn’t work with your stuff if you used those unsupported namespaces.

    That attitude is one of the main reasons why apps opened in Flex 3 that were created in Flex 2 have extremely little to change; we’re talking less than an hour for Enterprise apps.

    …the attitude still sucks, though. The Flex team gets bashed by people on this issue at every convention I’ve been to. There is some seriously good shit in mx_internal and private that causes monkey patched Flex frameworks to be floating around in some projects. For those uber-purists who refuse to touch the sacred internals, they either put in lame work-arounds that don’t work well, or just drop the idea. Both are seriously jacked… although, I definately support the former, hehe!

    My guess is, they perceive us as the loud minority mostly consisting of Flash malcontents. Whatever. Here’s my added 20 decibels.

    SO, back to my original point. To get custom chrome to work, I have to override an un-supported method, adding my custom skins to a supported, yet never fully working for antiAliasing exception reasons I never figured out to get the Panel to have custom chrome. I solved the text problem by making it an image; that was fun every time the text changed (in all fairness, wasn’t often) updating the PNG and refreshing. Doesn’t seem like a bad thing, but remember, Flex 2 was SLOOOOOOOWWWWW… then again, Flex 1 was worse; must be appreciative and all.

    …OR, you can create a custom container in Flash using the Flex Component Kit for Flash. I’m pretty sure this came out like 2 weeks after my project. Even if I had used it, there’s one problem: Container, while bad ass, is NOT Panel.

    When you are creating components for Flex, you need to leverage the Flex framework. To not do so wastes the effort what 15+ bad ass developers from all the other world spent over a year on. Re-writing things yourself may feel cool, but it’s probably already done, and done well, in the Flex SDK. Furthermore, you need to play nice with others. For smaller service level projects, you can get away with it. For larger endeavors where other developers will be using your code “as they’d expect Flex to work”, you’re custom versions just won’t fly for maintainability reasons. You increase the cost of maintainece by using non-standard Flex components.

    Naturally, writing that paragraph pisses me off, because while I agree, I grew up in Flash where this shiz is EASY. Making the 2 come together is extremely frustrating. While examples 1 and 2 are resolvable, #3 was a hack job. It looked and worked damn good, but I feel sorry for the poor bastard to dug into my BluePanel.as (remember, extending containers in MXML is lamesauce; even Flex 3 acts happier when you use AS to extend containers). If I were to do it over again, I probably wouldn’t change a thing; I learned a TON about the internals of Panel and Container. However, if it were a major client project ( I was working for friends at the time on a prototype project ), I’d just code the bastard myself in ActionScript 3, extending UIComponent, and only support an extremely small sub-set of styles. I would of been done in 1/10th the time, and we only used like 20% of the features of Panel; aka, putting controls in it… whoop-pu-dee-frikin-doo.

    Conclusions

    Anytime I run into a design challenge in Flex, my first reaction in the past was to just “figure out how to make it work”. My gut today is, “screw it… just code it myself”. I then remember back to the days of Flash MX when I’d go, “You know… this Scrollbar component sux. I could code this myself!” Laughingly, every version was missing a MAJOR feature. Version 1 had no arrows. Version 2, you couldn’t click on the scroll track. Version 3, didn’t have the scrollbar’s thumb grow and shrink to accomodate content. None of them even did scrolling right because my math was pathetic. After 2 weeks of re-inventing the wheel 3 times, I had a MAJOR respect for the component writers.

    That, and other experiences like it, combined with the implied maintaince costs vs. speed to market agile-is-t3h-buzzword… basically cause insane internal debates. Balancing pragmatism with your duty to strive for OOP Purism in these scenarios, EVEN AFTER you’ve asked the Designer for help, is really hard. “I can code this functionality faster myself… but at what cost down the road?”

    So far, the ratio has been hack/abandon crazy ideas 60%, do it yourself in a conservative way, 40%. That’s for the big Flex jobs. The rest, 90% do it yourself. This doesn’t always come up, mind you in every Flex project; it’s not a constant thorn. It IS a thorn, though, when you get a bad ass designer, specially one of those with Flash experience who’s already been spoiled by good Flash Developers, and the design just won’t fit. Save me Thermo, you’re my only hope… just don’t generate crap code, please!

  • PureMVC Frustrations and Code Behind Thoughts

    Over the holiday’s, I went to PureMVC.org to read over the documentation. PureMVC, although a year old, is the new framework on the block for developing Rich Internet Applications atop the Flash Player. There are plans to port the framework to other languages and runtimes like PHP & Silverlight in the future. Like Cairngorm, it’s a framework that uses coding conventions based on design patterns, namely the meta pattern, Model View Controller written in ActionScript 3. Unlike Cairngorm, however, it has no ties to the Flex SDK. This means you can use it with Flash CS3, Flex, or just pure ActionScript 3 projects.

    If you are a computer scientist, you’ll love the documentation. It’s chock full of design pattern discussions, justifications on framework implementations, and visual diagrams all in a nicely organized website. If you’re like me, the docs will get old after 30 seconds. I went straight to the example Flex project you can download to learn how it works.

    Upon digging, I found some familiar coding styles, and some unfamiliar. When I saw the use of View Mediators, however, I immediately got a bad taste in my mouth. I composed myself, and sent off a non-leading email off to Joe Berkovitz asking his opinion. I’m still waiting to hear back from Thomas B. I won’t speak for their replies, but it’s nice to know that not everyone finds PureMVC uber-perfect as the blogsphere’s reaction this past year has suggested.

    My first gripe is with View Mediator’s. A View is form, GUI, or some other visual control; it’s what the user sees in MVC. View’s can read from the Model, and ask the Controller to do things, inform the Controller of user events, and be informed by the Controller of the Model changing. A Mediator is a class that allows various classes to talk to each other without tight coupling. It is the de-facto design pattern in developing Flash & Flex applications. Farata Systems has a great post talking about it in context. A Flash Developer explanation is, “It’s a MovieClip that holds other MovieClip’s and allows them to talk to each other without them ‘knowing’ about each other”.

    In PureMVC, a View Mediator is created for each View. You don’t need to create this for all View’s since some via Composition (View’s used inside of other View’s) aren’t all that complicated and thus you don’t need to create all this code for such a simple class. The purpose of the Mediator as I’ve seen it used in the example Arch101Demo is to respond to Application state changes and/or events in the form of Notifications. Secondly, it can interact with Proxies to data; basically liaison’s to the data.

    There are a few problems I have with the first part. The Notifications contents are not strongly typed and thus suffer from the same problem that Cairngorm’s Delegates do that implement mx.rpc.IResponder. In Cairngorm, your Commands (classes that do Controller logic) can implement an interface called IResponder. This allows them to work with Delegate’s, classes that make web service calls. They return either a result or a fault. While the onFault is great in that you get back a FaultEvent that contains detailed failure information, ResultEvent is useless. You have to make assumptions on the data you get back since ResultEvent.result is cast as an Object. If I ask the server to give me a Person object matching an specific ID, I should get that back in my result event. If not, something went wrong, and my fault should be called. Instead, you have to force the Command (assuming you follow the standard Cairngorm Command way of implementing the IResponder interface) to “parse” data. Parsing data should not be in the realm of Controller logic, and instead be done strictly by services. Notification’s getBody, and other functions suffer from this same problem.

    It’s not the end of the world; people cast flash.display.Loader.content to what they “think” they are loading all the time. However, PureMVC had the opportunity to get things right here and they didn’t. The INotification interface’s list of functions (excluding getName) should at the very least return a type interface instead of Object. If you’re going to follow the whole “programming by contract” methodology, do it across the board and not just where you feel like it to support your framework.

    The other gripe is with ApplicationFacade events. You define Notification types (like Event types) that your Application will dispatch as constants. Your Mediator’s can then listen for these specific Notifications and react to them. This allows multiple Medator’s to listen to a single Notification. Whether they re-created their own event system instead of using Flash Player’s built in EventDispatcher system with custom Event classes for framework reasons, or whether they were trying to prevent application developers from burning themselves with un-registered Notification listeners causing memory leaks isn’t my main frustration. What is bad is that I fail to see how putting all of these events on ApplicationFacade will allow your application to scale in size.

    The whole reason you extend the AS3 Event class is to provide context to those who respond to those events. Some don’t care about context; for example, Application startup. However, when clicking on a List control, you need to know what item was selected, what was the previous item if any, what is the index of that item, and for View’s a strongly typed reference in case the Event bubbled up to you from a deeply nested View and you have no way to access the List in a parent child way. You can’t do that if you have a bunch of event names in the form of Notifications. Granted, you could package the payload into the Notification itself so it can act like an event, but the Notification has no strongly-typed way of doing that based on the INotification interface, and suddenly your packing in information into a Notification that others may not need. Granted part deux, yes, you could create your own Notification class, but explain to me why we’re not extending the built in Event class again? Event’s can bubble and be intercepted.

    Mediator’s have a reference to the View instance they are representing. The problem is, it’s up to the developer to handle this marriage. Cairngorm had something similar called a ViewHelper. It’s now deprecated, but the point of a ViewHelper was two-fold. First, it did the same thing Mediator’s in PureMVC try to do; greatly simplify the amount of logic in View’s. Second, they provide a non-GUI based class that can interact with others, preventing the View to have to know too much about the framework it’s in. In Cairngorm, they had an extra bonus of working well with a ViewLocator; a globally accessible class that allowed anyone to access a View’s ViewHelper by a magic string; it flattened the tree of GUI View’s.

    Mediator’s in PureMVC are definitely successful in those goals. If you look at their code and what the View’s in the example app are doing, it’s certainly more readable. There are also a lot less dependencies than say, Cairngorm where the second a View dispatches an event via CairngormEventDispatcher, it “knows” about Cairngorm.

    However, the down-side was in Cairngorm, ViewHelpers were created by the View’s. There was a 1 to 1 relationship that was instantiated when the GUI View was created. You couldn’t really screw that up. Although it was opt-in, a lot of people new to Flex just created 1 ViewHelper for every View. In PureMVC, they suggest you not only instantiate a Mediator yourself in a Command, but you also hand it the View instance yourself. While not major since ActionScript 3 allows us some strong-typing to ensure we “have the View we think we have”, why in the hell is not done for you? It’s an area where a developer can mess up; either they forget to actually create their Mediator, or pass in the wrong View reference. This is minor, but the whole point of a framework is to help you write less code, not more.

    Worse, what if I have multiple View’s? Do I then have to have each dispatch a new Notification (onUserEditViewCreate) just so I can create a new Mediator with a new View instance reference in a Command? WTF… the framework should handle these low-level details.

    The biggest gripe I have with PureMVC, and the one that made me all negative was how Mediator’s have access to Model Proxies. The ONLY person in MVC who should be able to SET data on the Model is the Controller. A Mediator, although merely having a reference to a View, IS associated with a View. It should NOT be setting data on the Model; the Commands should be doing this by listening to events (Notifications, whatever) dispatched from the Mediator’s. Just because a Command creates them doesn’t suddenly bequeath them Controller ‘esque powers. This is probably done this way because of my last gripe…

    …PureMVC Commands do not follow a true Controller pattern of setting data. One is instantiating a Mediator (StartupCommand) while the other is updating the Model (DeleteUserCommand). What the hell? I’d argue the DeleteUserCommand is correct, and the StartupCommand is wrong. In fairness, that’s because I’m comparing them to Cairngorm Commands. I’ll admit, this is the weakest argument I have, yet you have to agree it’s not consistent on what Commands are really for based on the example. Updating data? Creating things to have them update data? What if the Command wants to intercept the Notification and do something first, preventing the Mediator from doing it? Without a core Controller, you now have multiple types of classes setting data on Proxies. I can see it now… “Did I set the data in the Command or the Mediators…? Man, this’ll be a long morning…”.

    Thoughts on Code Behind

    On a side note, this is the second time I’ve seen a framework cater to a View code behind model. The theory and practice of code behind as it relates to Flex has been talked about and lauded a lot so I’ll leave it to Google to give you more details. The idea is that you utilize 2 classes or files; 1 for GUI and 1 for logic. The reasoning behind it is “separation of concerns”, the traditional computer science idea of making a large program easier to manage by breaking it up into pieces that each manage their area of interest. A lot of code in complicated View’s has absolutely nothing with drawing visual graphics to the screen, and is merely the logic behind the View. The current reason I don’t support this methodology in Flex is that FlexBuilder does not support it well.

    Silverlight & WPF on the other hand have tools built around this idea. In Blend, you control the actual real guts of the View; it’s layout, visual look, and transitions via XAML (like MXML). In Visual Studio, you code the logic behind it in C# or VB (like AS). In Flex, this currently feels forced. While convention helps, you don’t really get any help from the IDE in doing this methodology. This doesn’t bother me as I like coding my View’s to be 1 file and encapsulated. This can reduce readability, however, for complicated View’s that have a lot of code that doesn’t really relate directly to how the View displays itself.

    Cairngorm was the first framework I saw advocate this methodology via the aforementioned ViewHelper, leading me to believe that this is something Enterprise Java devs are used to doing. PureMVC is the second with the added twist of using the code behind not just as a separation of concerns, but also as a mediator the rest of the program that the View interacts with, hence the appropriate name. I typically use Mediator’s via Composition like Farata Systems linked above describes it. It is definitely a creative way of handling SoC and code behind in a framework way.

    Maybe if Thermo could create well written MXML and Flex 4 well written generated code-behind, I’d dig the idea and actually use it on projects.