November 23, 2009
Modularity in Flex Applications
There has been talk recently about the trend towards inversion-of-control frameworks in Flex. In addition to this, a higher-level movement can be seen towards modularity frameworks. Such an approach to architecture can bring many benefits, particularly in enterprise settings with larger teams and formal release processes. This post explains what modularity means in the context of Flex and discusses some of the benefits and options available for implementation.
What is Modularity?
Modularity is something more general than the Flex Module and ModuleLoader components. These are a form of modularity, but the principle is broader: modularity is about separating applications into smaller units that can be developed and deployed independently. In the context of Flex, these units might be modules, sub-applications or any other kind of encapsulated content. A modular application usually has a structure like that shown in Figure 1.

In the figure above, the application consists of a thin shell that loads three modules: Dashboard, Contacts and Messages. These modules represent different functional areas of the application. Their implementation detail is independent of one another. The application shell is responsible for loading and laying out the modules, and providing a means of communication between them. This might be a global data model, a registry of interfaces, or in the case of Figure 1, some kind of message bus.
What are the Benefits of Modularization?
Modularization can bring benefits for end-users of an application and also for the teams that develop and deliver them; Here are some of the benefits:
- A module can be developed, tested and profiled in relative isolation.
- Build times are shortened, since changes to one module don't require other modules or the shell application to be recompiled.
- Modules can be loaded on demand, so the initial download for an application is smaller.
- If a user never uses the features of one module, that module need not be loaded.
- Individual modules can be deployed into production, instead of redeploying an entire application.
- Different modules can be loaded for different users based on their entitlements.
- A module is easier to understand and maintain than a monolithic application, since it is more functionally cohesion.
- The interactions between modules can be confined to a thin API, reducing regression as an application grows.
The benefits in terms of architecture and development efficiency are arguably the most important. Small groups of developers can work on individual modules. The contracts of communication between modules can be agreed, so the implementation is free to change and improve without regression.
Framework Provisions for Modularization
Some frameworks have features to help with building modular applications. PureMVC was probably the first to do so with the multi-core version of the framework and its Pipes utility for controlled flow of messages between modules. The Parsley application framework is also designed to support modular applications, in which a module would normally have its own inversion-of-control context that inherits object definitions from the context of a shell application. Parsley includes a messaging framework that can be used for loosely-coupled communication between modules.
The other frameworks are hot on their heels. Spring Actionscript will have modular support as of version 0.9, where each module can have its own context with the option to inherit the object definitions of its parent. A parent context will be able to control which object definitions are exposed to a child context. And the lightweight Swiz framework is going to improve its support for modular development in the near future with its 1.0 release.
In addition to these established frameworks, there are some emerging frameworks focussed more specifically on modularity. Potomac and Adobe Gravity are two new frameworks inspired by OSGi, the dynamic module system for Java. Both aim to provide the infrastructure for loading bundles (i.e. modules) at runtime and communicating between them through service interfaces. Adobe Gravity remains an Adobe internal project but there are plans for a future open-source release, while Potomac is publicly available and includes some developer tooling in the form of a Flash Builder plug-in.
Cairngorm 3 and Modularization
One of the key messages of the Cairngorm 3 reference architecture (currently in draft) is to separate applications into distinct functional areas that can be developed independently; in other words a modular architecture, where each functional area is a module. The Cairngorm guidelines recommend that communication between functional areas takes place through a thin API that might consist of interfaces, events and data transfer objects. This approach minimizes dependencies between the distinct functional areas of an application. It promotes what Robert Martin terms "good dependencies" in the direction of stability. More details can be found in the Creating Functional Areas draft document.
The Enterprise Solution: Adobe LiveCycle Mosaic ES2
LiveCycle Mosaic ES2 is far more than a modularity framework, but modularity is an important part of its design. It's a client-and-server-side technology for building applications by composition, combining different pieces into personalized views that are focussed on the activities that different users perform. On the server-side, reusable application assets can be stored and shared, while LiveCycle DataServices is available for integrating with different data sources. On the client-side, applications are assembled from different tiles, that can be developed from scratch or adapted from existing Flex and HTML applications. A customizable shell application loads and lays out the tiles, and the framework provides a publish-subscribe messaging API for communication between them. For more details about the Adobe enterprise solution to modularity, refer to the LiveCycle Mosaic ES2 product page.
Conclusion
As we attempt to build bigger and better applications in Flex and AIR, the topic of modularity becomes more important to ensure efficient development, scalability and maintainability. It is vital to be able to separate portions of a large application so they can be developed, tested and deployed independently. The Flex SDK provides some simple means of modularization with Modules and Sub-Applications, and some frameworks build on top of these to provide more features. Furthermore, Adobe has now released an enterprise solution in LiveCycle Mosaic ES2 that provides the infrastructure for rapidly developing and deploying RIAs to the browser and desktop in a modular way.
Posted by tsugden at 10:32 PM | Comments (0)
September 21, 2009
Morgan Stanley Matrix at MAX
Next month at Adobe MAX 2009 in Los Angeles, Børre Wessel (Lab49) and myself will be presenting Matrix, the next-generation sales and trading platform from Morgan Stanley.

The session is entitled, "Building Matrix – Scaling Flex for a Large Trading Application" and it will cover our experiences as we worked on the client-side architecture of Matrix, together with a large team of developers. We will discuss the patterns and practices that made the delivery possible — modularization, dependency management, performance tuning, inversion-of-control, etc. — and the challenges we faced along the way, providing guidance for other large-scale enterprise Flex projects.
For more information, put on your headphones and check out the Morgan Stanley Matrix micro-site. Some other resources are listed below. Hope to see you there!
- Morgan Stanley raises the bar for rich Internet applications using Adobe Flash Platform technologies
- Morgan Stanley's Matrix: An App From the Future
- Morgan Stanley taps Adobe Flex framework for new trading platform
Posted by tsugden at 9:40 PM | Comments (2)
September 13, 2009
Coming Soon: Cairngorm 3
Cairngorm is about to undergo a transformation that will broaden its scope and increase its value to clients and partners. Instead of centering around a specific implementation of the Model-View-Controller pattern, Cairngorm 3 will consist of a set of best practices, tools and libraries, many of which apply across frameworks. This is the knowledge gathered by the Adobe Technical Services organization and partners over the last five or six years, condensed and presented to help others to deliver successful Flex projects in the enterprise.
For those familiar with the Cairngorm 1 & 2 micro-architecture, the traditional Cairngorm library remains a part of Cairngorm 3. Our best practices for applying the Cairngorm library will be shared, together with information about tried-and-tested extensions. And like before, Cairngorm 3 will recommend a layered architecture that separates concerns and supports test-driven development, but this time the approach has been refined and most parts of it complement multiple frameworks.
So what is Cairngorm now if it isn’t just a framework? Well it’s a foundation for delivering successful Flex projects. It’s the answer to the question, “What are the best practices for Flex in the enterprise?”, to help set new teams off on the right track. It’s the information that can’t always be found in official documentation or framework manuals. It's going to be accessible, informative and open-source. And it’s coming soon...
Posted by tsugden at 8:57 PM | Comments (5)
September 4, 2009
Eliminate Common Bad Practices with FlexPMD
Adobe Technical Services are pleased to release FlexPMD to the community. FlexPMD is a new open-source tool for improving code quality. It works by analyzing ActionScript and MXML source files to identify common bad practices, like over-long classes or functions, reliance on magic strings, unused parameters, and many other programming mistakes or misjudgments. It can even spot code that might be causing performance problems, and furthermore, the ruleset can be customized and extended, to include rules specific to the coding conventions of your own project.
FlexPMD can be launched from the command line, but the best practice is to invoke it from your Ant or Maven continuous integration build scripts. In this case, a report will be generated each time a build is performed, describing the violations of your chosen ruleset. As soon as someone checks in their fancy new 1,000 line algorithm with nested loops, numeric variable names and a gaggle of change-watchers, the red flag will be raised. The report produced by Flex PMD allows simple coding mistakes to be identified and corrected immediately, when the cost is far cheaper than attempting to refactor a system that has been decaying for months.

Another benefit of FlexPMD is that code reviews become more valuable. Since FlexPMD can automatically identify the common problems, code reviewers are left to reflect on the deeper issues, like domain modeling, separation of concerns, proper encapsulation, and so on.
To find out more about FlexPMD and start using it on your own projects, follow these links to Adobe Open Source:
- About FlexPMD
- Download FlexPMD
- How To Invoke FlexPMD
- How To Interpret FlexPMD Results
- How to Add Your Own Rule
Credit goes to Xavier Agnetti for conceiving and leading this effort, with support and contributions from many in the Technical Services organization and other parts of Adobe.
Posted by tsugden at 7:21 AM | Comments (0)
August 24, 2009
Applying the Presentation Model in Flex
Introduction
The purpose of the Presentation Model design pattern is simple to grasp: it’s a way of moving state and logic out of a view component and into another class, where it can be developed, comprehended and unit tested more easily. The pattern promotes a clean separation of concerns, helping to keep MXML views as structural definitions, free from Script-block logic. However, there are several ways to apply presentation models in Flex. Some of these can help us to build simpler, more testable systems, while others may lead towards entanglement and maintenance difficulties.
For a comprehensive introduction to the Presentation Model pattern and a comparison between it and other presentation patterns, please refer to Paul Williams' blog series on the topic. At Adobe Professional Services, we have found the Presentation Model to be well suited to Flex, since it takes advantage of language features like bindings and in-line event handlers, while side-stepping some of the difficulties of unit testing display objects.
This article discusses two approaches to applying the Presentation Model -- hierarchical and componentized -- and makes a recommendation in favour of the latter.
Two Approaches: Hierarchical or Componentized
Hierarchical
With the hierarchical approach to the Presentation Model (PM) pattern, a hierarchy of PMs is developed that reflects the hierarchy of view components, as shown in the Figure 1.

Each MXML view component has a corresponding PM. The parent view contains the child views, and likewise, the parent PM contains the child PMs. Below these View-to-PM pairs, there are only basic UI controls, implemented in ActionScript without corresponding PMs.
With this approach, the top-level PM is usually instantiated in the top level view. It may be a singleton to allow other parts of the application, such as commands to access it as required. The child PMs are then passed down manually into the child views, as shown below:
<example:MyComponent ... >
<mx:Script>
[Bindable] public var model:MyComponentPM;
</mx:Script>
<example:MyChildComponent model="{ model.myChildComponentPM }" ... />
...
</example:MyComponent/>
When a hierarchy of presentation models is established, coordination takes place by method calls between the PMs, sharing objects amongst them, and dispatching events up the hierarchy. So if a user selects an item from a DataGrid in View 2, a selectedItem property may be updated on PM 2 and an event dispatched to announce the selection. PM 1 may listen to this event and perform its own logic in response.
Componentized
With the componentized approach to the Presentation Model pattern, there is a single hierarchy of view components but no hierarchy of presentation models. Each view component has a corresponding presentation model, but these models are independent of one another, as shown in Figure 2.

With this approach, the PMs are usually injected into their corresponding views using the view-wiring mechanism of an IoC framework. For example, the following code could be used with Parsley 2:
<example:MyComponent ...
addedToStage="dispatchEvent(new Event('configureIOC', true'))">
<mx:Script>
[Inject]
[Bindable]
public var model:MyComponentPM;
</mx:Script>
<example:MyChildComponent/>
...
</example:MyComponent/>
Here the configureIOC event instructs Parsley to inject a presentation model instance, declared in a configuration file, into the model property of the view. Notice that there is no need to pass a model into the child component. Each component is self-contained and takes care of its own business.
A variation of this approach is to declare the presentation model directly in the view, as shown below:
<example:MyComponent ... >
<example:MyComponentPM id="model"/>
<MyChildComponent/>
...
</example:MyComponent/>
Although the presentation models are kept independent of one another with the componentized approach, there remains a need to coordinate the components in some way. This can best be achieved using an Inversion-of-Control (IoC) framework, such as Parsley, Swiz or Spring ActionScript. There are ways to do so:
- Messaging - route messages directly between the models using whatever mechanism your preferred framework provides. Parsley 2 includes a loosely-coupled messaging framework; Swiz has a notion of mediated events; while Cairngorm MVC has a singleton event dispatcher that can serve a similar purpose.
- Domain Interfaces - inject shared domain models into multiple PMs. Coordination then takes place when the PMs call methods on the interfaces to these models, and listen for events dispatched by them. All IoC frameworks support this feature.
- Controller/Presenter - use separate classes, known as controllers or presenters, to coordinate multiple PMs. These classes are typically injected with a number of presentation models, using an IoC framework. The controllers then listen for events and invoke methods on the PMs.
The relative merits of these are not discussed here, but will be tackled in another article. Each approach achieves a similar result of de-coupling the components from one another. The two approaches to the Presentation Model pattern are now compared in terms of their responsiveness to change.
Responsiveness to Change
It is common for the visual designs of a user interface to change during development, based on user feedback, client demands, or moments of creative inspiration from the designers. In my experience, this usually happens when I've just put the finishing touches on the implementation, the pixels are perfectly aligned and the unit tests running green! So it's important to write code in such a way as to minimize the cost of change, allowing components to be manoeuvred from place to place and logic to be reused without great effort.
Consider the case where a view component needs to move from one region of the user interface to another. Starting with the simple hierarchy shown earlier in Figure 1, changes are required to four classes, now highlighted in red in Figure 3.

View 3 needs to be detached from its starting place in View 1 and re-declared in View 2. Similarly, the reference to PM 3 contained in PM 1 needs be removed and introduced to PM 2. Any coordination logic that was in PM 1 also needs to be moved into PM 2.
In contrast, the componentized approach, first shown in Figure 2, responds more easily to change. Only the declaration of View 3 needs to be moved from View 1 to View 2, as highlighted in red in Figure 4.

Since the logic for the View-to-PM components is self-contained and coordination takes place externally, though messaging, domain interfaces, or controller/presenters, no further changes are necessary. If test-driven development is being practiced, the unit tests for the PMs also remain intact, whereas they would need to be refactored with the hierarchical approach.
Conclusion
The Presentation Model is a useful pattern for building testable Flex applications. By moving the state and logic used to present data and handle user gestures into PMs, it can be unit tested in isolation and understood more easily than Script-block logic placed directly within views. However, rich user interfaces can be somewhat volatile, changing their shape often during development, so it is recommended to apply a componentized version of the Presentation Model that is easy to adapt, rather than developing and ultimately maintaining a hierarchy of connected presentation models.
Posted by tsugden at 9:32 PM | Comments (5)
August 11, 2009
Best Practices for the Flex Logging Framework
Introduction
The Flex Logging Framework is easy to learn and flexible to use. It supports many different scenarios, from helping developers to debug their code, to sending the details of production application errors over the wire to a remote server for monitoring. To learn the basics of the Logging Framework refer to the latest Flex Developer Guide and the Flex Logging Framework chapter of Professional Flex 3. This document describes some best practices for applying the Logging Framework on enterprise projects.
The APIs provided by the Logging Framework are simple, but they need to be used properly to get the best out of them. If care is not taken, the benefits that logging can provide for debugging and monitoring an application in production can be lost. Performance problems can even be created. This article provides a set of best practices to keep the developers in your team on the right track.
Best Practices
The following best practices are covered:
- Get Loggers by Class
- Declare Loggers as Static Constants
- Format Log Statements Consistently
- Parameterize Log Statements with Tokens
- Use Log Levels to Indicate Severity
- Use Log Filters for Focus
- Include Categories to Show Class Names
- Use Guard Conditions Appropriately
- Configure Logging at Runtime
Get Loggers By Class
Use a simple utility method to retrieve the logger for a particular class, instead of passing in the qualified class name as a string.
Good:
private static const LOG:ILogger = LogUtil.getLogger(MyClass);
Bad:
private static const LOG:ILogger = Log.getLogger(“my.package.MyClass”);
With the utility method approach, the class name can be refactored without needing to edit the string. Here is an implementation for the LogUtil.getLogger() method:
public static function getLogger(c:Class):ILogger
{
var className:String =
getQualifiedClassName(c).replace("::", ".")
return Log.getLogger(className);
}
If performance profiling shows this method call to be a performance bottleneck, you may decide to revert to passing in the class name manually, since this will run a little faster. However, in most cases the convenience and refactor-ability of the above approach is the best practice.
Declare Loggers as Static Constants
In most cases, log statements apply to a particular class, so a logger should be declared as a static constant and not an instance variable.
Good:
private static const LOG:ILogger = LogUtil.getLogger(MyClass);
Bad:
private var log:ILogger = LogUtil.getLogger(MyClass);
Format Log Statements Consistently
Log statements should be formatted consistently and not haphazardly. This ensures that logging code looks professional and improves readability of log files (for humans or machines).
Good:
LOG.error(
"Something bad has happened: event={0}, message={1}",
event.type,
message);
Bad:
LOG.error("----------- SOMETHING BAD HAS HAPPENED! -----------------");
Parameterize Log Statements
Parameterize log statements using the rest parameter and tokens, instead of appending strings manually. This produces cleaner code and prevents the composite string from being assembled in the event that no log target is registered.
Good:
LOG.debug(
"Something interesting is happening: event={0}, message={1}",
event.type,
message);
Bad:
LOG.debug(
"Something interesting is happening: event=" +
event.type +
", message=" +
message);
Use Log Levels to Indicate Severity
Use the debug/info/warn/error log levels to indicate the severity of the message, instead of emphasizing important messages with special characters.
Good:
LOG.error("The service has failed and no data is available.");
Bad:
LOG.debug("!!! ERROR !!! The service has failed !!! ERROR !!!");
Use Log Filters for Focus
Set the log filters on your logging targets in order to focus on the logs produced by a certain part of the system. Do not instead try to make certain log statements stand-out with special characters. Remember to keep the format of log messages consistent.
Good:
target.filters = [ "my.important.package.MyClass" ];
target.level = LogEventLevel.INFO;
...
LOG.info("My important message");
Bad:
LOG.debug("----------- My really important message! -----------");
LOG.debug("<<<<<<< another super important log! >>>>>>>>");
LOG.debug("************* CAN YOU SEE ME????? ***************");
The trouble with the “special character” approach is that what is important for one developer one day is different to what is important for another developer on another day. If every developer uses their own notation for making their logs stand-out, the resulting log file becomes harder to read than when no emphasis has been placed in the text. Log levels and filters provide a more controllable and consistent mechanism for the same purpose.
Include Categories to Show Class Names
If you want to see the name of the class issuing a log statement, include categories for your log targets. Do not instead hard-code the name of the class into log statements.
Good:
target.includeCategory = true;
...
LOG.debug("Executing command");
Bad:
LOG.debug("<<< Executing SynchronizationCommand >>>");
The bad practice above is not refactor-safe. If the class is renamed, the message becomes confusing and if categories are included in the output, part of the message becomes redundant.
Use Guard Conditions Appropriately
Use guard conditions to prevent unnecessary processing where a log statement is expensive or nested within a loop or iteration. However, do not use guard conditions around every single log statement since this clutters up code. Decide whether or not the log statement may be expensive or use the profiler to verify this.
Good:
if (Log.isDebug())
{
LOG.debug("Result received: {0}", ObjectUtil.toString(model));
}
for (var i:int = 0; i<10000; i++)
{
if (Log.isDebug())
{
LOG.debug("Blah blah blah: i={0}", i);
}
}
Bad:
LOG.debug("Result received: {0}", ObjectUtil.toString(model));
for (var i:int = 0; i<10000; i++)
{
LOG.debug("Blah blah blah: i={0}", i);
...
}
In the bad practice above, the model will be converted into a string even if there is no registered target for the debug-level. Similarly, 10,000 log statements will be issues inside the loop regardless of whether or not there is a target registered.
Configure Logging at Runtime
Configure logging at runtime is a best practice, since it allows developers to change their log filters without rebuilding and also allows logging to be reconfigured in production without redeploying. Different log settings can even be applied to different users.
The process for configuring logging at runtime is beyond the scope of this article, however, the Parsley 2 Application Framework provides a feature for doing precisely that by loading an external XML file that specifies the targets, levels and filters. There are also examples available showing how to do the same thing using Prana/Spring ActionScript.
Posted by tsugden at 9:15 AM | Comments (2)
July 18, 2009
A Declarative Approach to Flex Popups
Yaniv De Ridder and myself have developed a small Flex library for opening and closing popups. Instead of using the PopUpManager directly and writing script-block logic to manage their creation and removal, a pair of simple MXML tags are available for declaring within view components. Here's the "Hello World" of declarative popups:
<popup:PopUpWrapper open="{model.openPopUp}">
<mx:Label text="Hello World"/>
</popup:PopUpWrapper>
The PopUpWrapper tag is a non-visual component that manages opening and closing the popup. When its open property is set to true, a popup is opened containing the component wrapped by the tag; in this case a Label. When the open property is set back to false, the popup closes again. Alternatively, the component may dispatch an Event.CLOSE event, which will be handled by the PopUpWrapper itself.
This approach helps to keep MXML views components clean and free from ActionScript logic, whilst removing duplicated code wherever the PopUpManager is needed. The opening and closure can be controlled conveniently through bindings, as above, which plays nicely with presentation models. There are also simple ways to control the life-cycle of the popup and to apply special behaviors, such as effects that play while it opens and closes.
The remainder of this post covers the two components available -- PopUpWrapper and PopUpFactory -- explaining the differences between them. The library, source code, unit tests and a sample application are available for download here:
- FlexPopUpWrapper.swc - the SWC library compiled with Flex 3.3.
- FlexPopUpWrapper - a Flex library project containing the source for the two components.
- FlexPopUpWrapperExample - a Flex application project containing a sample application.
- FlexPopUpWrapperUnitTests - a Flex application project containing the unit test runner for the FlexPopUpWrapper library.
Using Declarative Popups
There are two components with slightly different capabilities:
- PopUpWrapper - this is the simplest tag. It defers the creation of the popup view until the first time the popup is opened, then reuses the same view every subsequent time. There is no mechanism for releasing that view to be garbage collected.
- PopUpFactory - this is the more flexible but less simple tag. It also defers creation of the popup view, but gives control over whether or not the view should be reused when the popup is next opened. If reuse is disabled, the view is made eligible for garbage collection upon closure.
Some examples of each are now provided.
The PopUpWrapper Component
Here's a more detailed version of the "Hello World", this time showing all of the properties and events available:
<popup:PopUpWrapper
open="{model.openPopUp}"
center="true"
modal="false"
childList="{PopUpManagerChildList.POPUP}"
opening="openingHandler()"
opened="openedHandler()"
closing="closingHandler()"
closed="closedHandler()">
<mx:Label text="Hello World!"/>
<popup:PopUpWrapper>
The properties provide the same control over the popup as the PopUpManager. The events are dispatched at various points during the life-cycle of a popup:
- PopUpEvent.OPENING is dispatched after the popup view has been created but just before it has actually been added to the display list.
- PopUpEvent.OPENED is dispatched just after the popup view has been added to the display list.
- PopUpEvent.CLOSING is dispatched just before the popup view is removed from the display list.
- PopUpEvent.CLOSED is dispatched just after the popup view has been removed from the display list.
Here's another example where the popup is opened or closed using buttons instead of binding. The view used for the actual popup is a custom component.
<popup:PopUpWrapper id="popup">
<mypopup:MyPopupView/>
</popup:PopUpWrapper>
<mx:Button label="Open" click="popup.open = true"/>
<mx:Button label="Close" click="popup.open = false"/>
The popup view itself can also instruct the closure of the popup by dispatching an Event.CLOSE event. For example:
<mypopup:VBox ... >
<mx:Label text="My Popup!"/>
<Button
label="Close"
click="dispatchEvent(new Event(Event.CLOSE))"/>
</mypopup:VBox>
The PopUpFactory Component
The PopUpFactory tag uses a different mechanism for specifying the popup view. It is in fact the same approach that list-based controls use for their item renderers. The factory property can either be set to the class name for the popup view, or else an in-line component can be declared.
Here is a simples use case, specifying the popup view class name:
<popup:PopUpFactory
open="{model.openPopUp}"
factory="my.package.MyPopupView"
reuse="false"/>
Notice that the PopUpFactory includes a reuse property. This gives control over whether or not the popup view is reused, in contrast to the PopUpWrapper tag which always reuses the view and never makes it eligible for garbage collection.
When working with the PopUpManager directly it is common to make popups eligible for garbage collection once they have been removed. However there are good use cases for both approaches. If an application shows a large popup at start-up and then never again, it is wasteful of resources to keep it in memory. Alternatively, if a popup is repeatedly shown and hidden, such as a context menu, it is more efficient to reuses a single instance. As with all Flex development, the Flex Profiler should be used to ensure popup views are successfully garbage collected, since they can be a source of memory leaks.
Here is another example where the popup view is declared as an in-line component, in a similar manner to an item renderer on a list-based control.
<popup:PopUpFactory
open="{model.openPopUp}"
reuse="false">
<mx:Component>
<mypopup:MyPopupView
title="{outerDocument.model.popUpTitle}"/>
</mx:Component>
</popup:PopUpFactory>
The PopUpFactory tag also provides the same properties as the PopUpWrapper tag, since they both inherit from a common base class.
Popup Behaviors
When we first introduced a declarative approach for popups to our projects, we noticed developers customizing the classes with more and more specific behavior. In one situation, a popup needed to play a transition while opening; in another the popup had to remain centered whenever its contents resized. Soon the popup tags became bloated with code for handling all of these special requirements, each applicable only to one or two popups.
The IPopUpBehavior interface was introduced to extract these specialities into their own classes. In this way, a set of behaviors can be created, independent of one another, and the appropriate behaviors can be applied for a given situation. This design creates a nice extensibility point, allowing developers to write their own behaviors without needing to customize the declarative tags at all.
Here is an example of a popup with a number of behaviors applied.
<popup:PopUpFactory
open="{model.showPopUp}"
factory="my.package.MyPopUpView">
<popup:behaviors>
<mx:Array>
<popup:ZoomAndFadePopUpBehavior/>
<popup:KeepCenteredPopUpBehavior/>
</mx:Array>
<popup:behaviors>
</popup:PopUpFactory>
In this case, two custom popup behaviors are being applied. The first plays a zoom and fade effect upon opening and closure, while the second ensures that the popup remains centered whenever its contents is resized. The declarative approach makes it simple to configure these behaviors.
To write your own popup behavior, just implement the IPopUpBehavior interface:
public interface IPopUpBehavior
{
function apply(opener:PopUpBase):void;
}
A reference to the popup component is passed through the apply() method to each behavior. The behavior can then attach event handlers in order to control the behavior of the actual popup while it is opened or closed. Some examples are provided in the sample project (download above). A behavior can also suspend and resume closure by calling the suspendClosure() and resumeClosure() methods of the PopUpEvent class. This allows something asynchronous, such as the playing of an effect, to take place during closure, before the popup is actually removed from the display list.
How Does It Work?
The design for the popup tags is relatively simple. There's a common base class -- PopUpBase -- that is extended by the two tags: PopUpWrapper and PopUpFactory. The base class contains the common properties -- open, center, modal -- and also holds an array of behaviors, applying them during opening and closure. The two concrete tags implement different creation and destruction policies using the standard mechanisms for deferred instantiation and object factories: IDeferredInstance and IFactory. The Flex compiler takes care of the rest, converting the declared popup view into an appropriately configured DeferredInstanceFromFunction/Class or ClassFactory object. See the Flex Language Reference for more details.
Conclusion
We've been using versions of these tags on our projects for several years now. They help us to separate concerns, keeping our views as simple declarations of components, free from script block logic that would make them harder to understand and more difficult to unit test.
It's worth noting that Flex 4 includes its own declarative tag -- PopUpAnchor -- which also takes advantage of MXML and deferred creation, but it is designed for drop-down menu scenarios. There are some similarities, but the PopUpWrapper and PopUpFactory components are designed for more general popup handling. Perhaps a future version of the SDK will include declarative tags that make it simple to manage the life-cycle of popups and apply different behaviors, but in the meantime we hope you enjoy using these components.
Posted by tsugden at 10:07 PM | Comments (4)
