Whether you are new to Adobe ® Flex ® or have been developing for a while, frameworks can help you get organised quickly.

Below is a list of Flex and AIR frameworks that will allow you to get up and running and develop highly-collaborative applications. The introductions are by the frameworks themselves, but I’d like to here from you about your experiences using them.

Cairngorm

Cairngorm is the lightweight micro-architecture for Rich Internet Applications built in Flex or AIR. A collaboration of recognized design patterns, Cairngorm exemplifies and encourages best-practices for RIA development advocated by Adobe Consulting, encourages best-practice leverage of the underlying Flex framework, while making it easier for medium to large teams of software engineers deliver medium to large scale, mission-critical Rich Internet Applications.

More information can be found on the Cairngorm project’s website.

PureMVC

PureMVC is a lightweight framework for creating applications based upon the classic Model-View-Controller concept.

Based upon proven design patterns, this free, open source framework which was originally implemented in the ActionScript 3 language for use with Adobe Flex, Flash and AIR, has now been ported to nearly all major development platforms.

Two versions of the framework are supported with reference implementations; Standard and MultiCore, though only the Standard version has been ported to other languages so far.

More information can be found on the PureMVC project’s website.

Mate

Mate is a tag-based, event-driven Flex framework.

Flex applications are event-driven. Mate framework has been created to make it easy to handle the events your Flex application creates. Mate allows you to define who is handling those events, whether data needs to be retrieved from the server, or other events need to be triggered.

In addition, Mate provides a mechanism for dependency injection to make it easy for the different parts of your application to get the data and objects they need.

More information can be found on the Mate project’s website.

Swiz

Swiz is a framework for Adobe Flex that aims to bring complete simplicity to RIA development. Swiz provides Inversion of Control, event handing, and simple life cycle for asynchronous remote methods. In contrast to other major frameworks for Flex, Swiz imposes no J2EE patterns on your code, no repetitive folder layouts, and no boilerplate code on your development. Swiz represents best practices learned from the top RIA developers at some of the best consulting firms in the industry, enabling Swiz to be simple, lightweight, and extremely productive.

More information can be found on the Swiz project’s website.

Guasax

Guasax is an ease of use programming framework which provides the creation of an ordered and scalable application with Adobe Flex. The lifecycle of the Guasax framework is based in the MVC pattern to take on our program actions. The Guasax framework helps you to maintain your business logic tier highly decoupled from your presentation logic tier.

Guasax takes reflection and introspection techniques as well as the Inversion of Control (IoC) pattern to execute the operations which we have pointed at and to make a decision about itself. Guasax is not intrusive on your class model. You don’t have to extend your classes in a framework class to use it.

More information can be found on the Guasax project’s website or on their Google code project.

Model-Glue: Flex

Model-Glue: Flex brings implicit invocation, Model-View-Controller design, and cleaner, less repetitive integration with backend services to Flex and AIR applications.

It shuns repetitive, boilerplate code in favor of helper classes and expressive APIs.

More information can be found on the Model-Glue: Flex project’s website.

In a previous post, I demonstrated how to implement Dylan Verheul’s jQuery Autocomplete plugin. Not content with demonstrating one library’s plugin, it is now the turn of MooTools.

MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

In this post I will show you how to implement the AutoCompleter plugin by Harald Kirschner. Kirschner’s AutoCompleter plugin script for MooTools provides the functionality for text suggestion and completion. It features different data-sources (local, JSON or XML), a variety of user interactions, custom formatting, multiple selection, animations and much more.

The Goal

The goal of this post will be the same as the jQuery autocomplete post: Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.

Prerequisites

  1. The latest copy of MooTools
  2. A basic understanding of JavaScript and JSON
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo below will show how to interact with a simple ColdFusion script, but I’ll also provide more (advanced) examples in the download.

How It Works

Once the user begins to type into the form text input field, the MooTools auto-complete is activated. After a set character length and time interval (both optional), a list of items is displayed below the input field. The user can select an item with either the arrow keys or mouse.

NB. Clicking back in the input field will repopulate the auto-complete list, if options are available, so that the user can change the selection. Deleting part of the chosen item will also trigger a new selection list.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The MooTools JavaScript.

HTML Form

<h1>Example: Country Lookup</h1>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>

ColdFusion

Below is a simple ColdFusion component that takes a string as an argument. This string is part or all of the country name. The query results are parsed as an array and returned from the function, as JSON, to the MooTools auto-complete function.

<cfcomponent output="false">
 
	<cffunction name="getCountry" access="remote" output="false" returntype="array" returnformat="json">
		<cfargument name="country" type="string" required="true" />
 
		<cfset var qryCountry = queryNew('country') />
		<cfset var arrCountry = arrayNew(1) />
 
		<cfquery name="qryCountry" datasource="test">
		SELECT countryName
		FROM country
		WHERE countryName LIKE <cfqueryparam value="%#ARGUMENTS.country#%" cfsqltype="cf_sql_varchar" />
		</cfquery>
 
		<cfloop query="qryData">
			<cfset arrCountry[currentRow] = qryCountry.countryName[currentRow] />
		</cfloop>
 
		<cfreturn arrCountry />
	</cffunction>
 
</cfcomponent>

JavaScript

The JavaScript will attach itself after the DOM is ready — this more or less relates to when the page has loaded in the browser. Each time the text input field, with the ID of country, is changed, the Autocompleter.Ajax.Json event is fired. This makes a call to the ColdFusion component, which returns a JSON object of matched items. This JSON object is interpreted by the plugin and rendered as an HTML un-ordered list.

<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="Observer.js"></script>
<script type="text/javascript" src="Autocompleter.js"></script>
<link rel="stylesheet" href="Autocompleter.css" type="text/css" media="screen" />
<script type="text/javascript">
window.addEvent('domready', function() {
	new Autocompleter.Ajax.Json(
		'country',
		'data/Country.cfc?method=getCountry&returnformat=json&country=' + $('country').getProperty('value')
		, {
			'minLength': 1, // We wait for at least one character
			'overflow': true // Overflow for more entries'
	});
});
</script>

Where to Take it Next

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the MooTools autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.

Download the Code

The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.

Creating an autocomplete form field historically has not been a trivial matter and would require an indepth knowledge of JavaScript and CSS. However, the task is made far more simple when using one of the many freely-available JavaScript libraries. In this post I will show you how to implement the jQuery Autocomplete created by Dylan Verheul.

The Goal

Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.

Prerequisites

  1. The latest copy of jQuery
  2. A basic understanding of JavaScript
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo will specifically look at a simple form text input field, which takes a country name.

See the demo, and others, in action

How It Works

Once the user begins to type into the form text input field, the jQuery autocomplete is activated. After a set time interval, a list of items is displayed below the input field. The user can select these with either the arrow keys or mouse.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The jQuery & JavaScript.

HTML Form

<h3>Example 1.: Country Lookup</h3>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>
<p>NB. If you have <a href="http://getfirebug.com/" title="Get Firebug">Firebug</a> installed you will be able to view the <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> call.</p>

ColdFusion

This is a simple example, using a database to return a list of country names that match the characters the user has input. You could expand this and return a JSON data structure.

<cfsetting enablecfoutputonly="true">
<cfquery name="qryGetCountry" datasource="myDatasource">
SELECT countryName
FROM Country
WHERE countryName LIKE <cfqueryparam value="#URL.q#%" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfoutput query="qryGetCountry">
#qryGetCountry.countryName##chr(10)#
</cfoutput>

JavaScript

The JavaScript will attach itself after the document is ready, i.e. after the page has loaded. Each time the text input field, with the ID of country, is changed, the autocomplete event is fired. This makes a call to the ColdFusion page, which returns a list of matched items.

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<link type="text/css" href="autocomplete.css" rel="stylesheet" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
	$("#country").autocomplete(
		"country.cfm",
		{
			minChars:2,
			delay:200,
			autoFill:false,
			matchSubset:false,
			matchContains:1,
			cacheLength:10,
			selectOnly:1
		}
	);
);
</script>

Where To Take It Next

JSON

The above example only shows a simple text list, separated by carriage returns. It is more preferable to use JSON.

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the jQuery autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.

Download The Code

The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.

Among the plethora of JavaScript libraries to have been released, few have been recognised to be as effective as jQuery. This lightweight library has been the subject of different discussions since it was launched in 2006. Basically, jQuery has the ability to flawlessly string together JavaScript together with HTML. Because of its effectiveness, there have different types of lightweight applications and plug-ins launched using jQuery. Ajax based websites that offers simple interface would virtually work together using jQuery’s simple interface.

Download the jQuery 1.2 API Reference (360KB).

More information can be found on the jQuery Website.

The ActionScript reference for rich Internet application development provides an alphabetical reference for all native ActionScript APIs for the Adobe technology platform runtimes: Adobe Flash Player and Adobe AIR—as well as the Adobe Flex framework APIs. Use this guide both as an API reference and a tool to learn about the ActionScript APIs available within the runtimes.

Download the ActionScript reference for RIA development (PDF 1.3MB)

The Adobe technology platform contains two primary runtimes. Flash Player is browser-based, and Adobe AIR is desktop-based. Because Adobe AIR is built on top of Flash Player, the Flash Player APIs are available within Adobe AIR. Consequently, Adobe AIR APIs are not available within Flash Player. The Flex framework is built on top of the Flash Player APIs, so it runs in both Flash Player and Adobe AIR. However, a number of Flex APIs take advantage of AIR APIs, and thus work only within Adobe AIR.

More information about this guide can be found on the Adobe Developer Centre Website.

With the release of ColdFusion MX 7 came the introduction of the Application.cfc ColdFusion component. This component replaced the traditional Application.cfm and OnRequestEnd.cfm ColdFusion application templates. Furthermore, if Application.cfc is present, both of these templates are ignored by the application.

In addition to replacing the Application.cfm, the Application.cfc introduced a number of built in methods that handle specific events. These events, as discussed in detail below, allow for a greater control over events within the application.

Application Variables

The THIS scope in the Application.cfc contains several built-in variables that allow you to set the properties of the application.

The following cfscript briefly outlines the variables that you can set to control the application’s behaviour.

<cfscript>
//the application name (should be unique)
THIS.name = "ApplicationName";
//how long the application variables persist
THIS.applicationTimeout = createTimeSpan(0,2,0,0);
//define whether client variables are enabled
THIS.clientManagement = false;
//where should we store them, if enabled?
THIS.clientStorage = "registry"; //cookie||registry||datasource
//define where cflogin information should persist
THIS.loginStorage = "session"; //cookie||session
//define whether session variables are enabled
THIS.sessionManagement = true;
//how long the session variables persist?
THIS.sessionTimeout = createTimeSpan(0,0,20,0);
//define whether to set cookies on the browser?
THIS.setClientCookies = true;
//should cookies be domain specific
//i.e. *.domain.com or www.domain.com
THIS.setDomainCookies = false;
//should we try to block cross-site scripting?
THIS.scriptProtect = false;
//should we secure our JSON calls?
THIS.secureJSON = false;
//use a prefix in front of JSON strings?
THIS.secureJSONPrefix = "";
//used to help ColdFusion work with missing files
//and directory indexes. tells ColdFusion not to call
//onMissingTemplate method.
THIS.welcomeFileList = "";
//define custom coldfusion mappings.
//Keys are mapping names, values are full paths
THIS.mappings = structNew();
//define a list of custom tag paths.
THIS.customTagPaths = "";
</cfscript>

Method Summary

Below is a brief discussion of the built-in event methods available to the Application.cfc. Since the Application.cfc is a regular ColdFusion component, you can also implement your own methods alongside the built in ones (assuming the names are uniquely different).

The onApplicationStart Method

Runs when the application first starts up: when the first request for a page is processed or the first CFC method is invoked by an event.

<cffunction name="onApplicationStart" returnType="boolean" output="false">
	<cfreturn true />
</cffunction>

This method is typically used to initialise code; for example to to set variables, such as datasource, into the APPLICATION scope, or create Singleton instances of ColdFusion components.

For example:

The following example creates structures in tha application scope to store general configuration settings and Singleton objects that can be later referenced by the application framework.

<cffunction name="onApplicationStart" returnType="boolean" output="false">
	<cfscript>
	// INITIALISE CONFIGURATION VARIABLES AND APPLICATION BUSINESS COMPONENTS
	// **********************************************************************
	// LOAD COMMON SITE VARIABLES INTO APPLICATION SCOPE
	// create structure to hold configuration settings
	APPLICATION.strConfig = structNew();
	//site-wide datasource(s)
	APPLICATION.strConfig.datasource = "DatasourceName";
	// default records per page for pagination
	APPLICATION.strConfig.recordsPerPage = 15;
	// **********************************************************************
	// LOAD PERSISTENT OBJECTS INTO APPLICATION SCOPE
	// data for object instantiation
	strArgs	= structNew(); // flush strArgs
	strArgs.datasource = APPLICATION.strConfig.datasource;
 
	// create structure to hold objects
	APPLICATION.strObjs = structNew();
	APPLICATION.strObjs.objUserManager = createObject("component","com.whatley.user.UserManager").init(argumentCollection=strArgs);
	//etc...
 
	// instantiate utility service objects
	APPLICATION.strObjs.objEmailServices = createObject("component","com.whatley.service.Email");
	APPLICATION.strObjs.objFileServices = createObject("component","com.whatley.service.File");
	APPLICATION.strObjs.objQueryServices = createObject("component","com.whatley.service.Query");
	//etc...
 
	// native coldfusion objects
	APPLICATION.strObjs.objServiceFactory = createObject("java","coldfusion.server.ServiceFactory");
 
	// **********************************************************************
	return true;
	</cfscript>
</cffunction>

Since the objects above are created as Singletons, we do not have to create or destroy objects throughout the application, but simply reference the object held in memory. This is efficient, but of course, would not be suitable for per-session objects, such as shopping carts.

For example:

Referencing and invoking an object from the APPLICATION scope:

<cfinvoke object="APPLICATION.strObjs.objUserManager" method="getUser" returnvariable="qryGetUser">
	<cfargument name="userId" value="#SESSION.strUser.userId#" />
</cfinvoke>

The onApplicationEnd Method

Runs when the application stops: when the application times out or the service is stopped.

<cffunction name="onApplicationEnd" returnType="void" output="false">
	<cfargument name="applicationScope" required="true" />
</cffunction>

This method is typically used to clean-up currently activities, save the current state of the application to a database or log the application’s end to a file. The latter can be useful to help determine when and why an application ended.

Below is a simple example of how you could implement a simple log:

<cffunction name="onApplicationEnd" returnType="void" output="false">
	<cfargument name="applicationScope" required="true" />
        <cflog file="#THIS.Name#" type="Information"
        	text="Application #ARGUMENTS.applicationScope.applicationName# Ended" />
</cffunction>

Notes:

  • The method is not associated with an individual request so you cannot use it to display data to a user.
  • If you call this method explicity, ColdFusion does not end the application, but does execute the code within the method.
  • The method can access the SERVER scope directly, but does not have access to the SESSION and REQUEST scopes.

The onMissingTemplate Method

Triggered when the user requests a ColdFusion template that doesn’t exist.

<cffunction name="onMissingTemplate" returnType="boolean" output="false">
	<cfargument name="targetpage" required="true" type="string" />
	<cfreturn true />
</cffunction>

ColdFusion invokes this method when it encounters a file not found condition, that is, when a URL specifies a CFML page that does not exist. This is an important addition to ColdFusion 8 and allows missing template errors (also known as HTTP 404 errors) to be captured more efficiently by the application framework.

The onRequestStart Method

Runs before the request is processed.

<cffunction name="onRequestStart" returnType="boolean" output="false">
	<cfargument name="thePage" type="string" required="true" />
	<cfreturn true />
</cffunction>

This method is great for user authorisation and login handling and for request specific variable initialisation. For example, you could use this method to log statistics to a database (performance and usage).

As this method runs at the beginning of a request, we can also use it to fire other events. In the example below, I reinitialise the Application which enables me to refresh objects held in memory that may have changed during code development or release.

<cffunction name="onRequestStart" returnType="void" output="false">
	<cfscript>
	//flush the application scope
	if ((CGI.server_name == "localhost") || (structKeyExists(URL,'refresh') && structKeyExists(URL,'password') && URL.password == "p455w0rd"))
	{
		onApplicationStart();
	}
	return true;
	</cfscript>
</cffunction>

The onRequest Method

Runs before the request is processed, but after onRequestStart.

<cffunction name="onRequest" returnType="void">
	<cfargument name="thePage" type="string" required="true" />
	<cfinclude template="#ARGUMENTS.thePage#" />
</cffunction>

This event handler provides an optional request filter mechanism for ColdFusion page requests. Use it to intercept requests to target pages and override the default behavior of running the requested pages. You can use this method to do preprocessing that is required for all requests. Typical uses include filtering and modifying request page contents (such as removing extraneous white space), or creating a switching mechanism that determines the exact page to display based on available parameters.

The onRequestEnd Method

Runs at the end of the request when all pages have been processed.

<!--- Runs at end of request --->
<cffunction name="onRequestEnd" returnType="void" output="false">
	<cfargument name="thePage" type="string" required="true" />
</cffunction>

This method can be useful for gathering performance metrics, or for displaying dynamic footer information (although I wouldn’t generally put display code in an Application.cfc).

For example:

Log the CGI variables to a database table.

<cffunction name="onRequestEnd" returnType="void" output="false">
	<cfset var qryInsertStats = queryNew('tempCol')>
	<cfquery name="qryInsertStats" datasource="#APPLICATION.strConfig.datasource#">
	INSERT INTO tbl_site_stats (template,query_string,referer,user_agent,remote_addr,datetime)
	VALUES
	(
		<cfqueryparam value="#CGI.PATH_INFO#" cfsqltype="cf_sql_varchar" />
		<cfqueryparam value="#CGI.QUERY_STRING#" cfsqltype="cf_sql_varchar" />
		<cfqueryparam value="#CGI.HTTP_REFERER#" cfsqltype="cf_sql_varchar" />
		<cfqueryparam value="#CGI.HTTP_USER_AGENT#" cfsqltype="cf_sql_varchar" />
		<cfqueryparam value="#CGI.REMOTE_ADDR#" cfsqltype="cf_sql_varchar" />
		<cfqueryparam value="#now()#" cfsqltype="cf_sql_datetime" />
	)
	</cfquery>
</cffunction>

The onError Method

Triggered when an error is encountered that is not caught by a try/catch block.

<!--- Runs on error --->
<cffunction name="onError" returnType="void" output="false">
	<cfargument name="exception" required="true" />
	<cfargument name="eventname" type="string" required="true" />
	<cfdump var="#ARGUMENTS#" />
        <cfabort />
</cffunction>

This method is used to handle errors in an application-specific manner. This method overrides any error handlers that you set in the ColdFusion Administrator or in cferror tags. It does not override try/catch blocks.

For example:

The following displays a friendly, static error page to the user if it is not a development server whilst also logging the error. If the error is on development, simply dump the error to screen for debugging.

<cffunction name="onError" returnType="void" output="true">
	<cfargument name="exception" required="true" />
	<cfargument name="eventName" type="string" required="true" />
	<cfif CGI.server_name neq "localhost" and CGI.server_name neq "127.0.0.1">
		<!--- Live application, handle error --->
		<cfinclude template="error/error.htm">
		<!--- Log all errors. --->
	        <cflog file="#THIS.Name#" type="error"
	            text="Event Name: #ARGUMENTS.Eventname#" >
	        <cflog file="#THIS.Name#" type="error"
	            text="Message: #ARGUMENTS.Exception.message#">
	        <cflog file="#THIS.Name#" type="error"
	            text="Root Cause Message: #ARGUMENTS.Exception.rootcause.message#">
	<cfelse>
		<!--- dump error for Staging and Development --->
		<cfif len(ARGUMENTS.eventName)>
			<cfdump var="#ARGUMENTS.eventName#" />
		</cfif>
		<cfdump var="#ARGUMENTS.exception#" />
	</cfif>
</cffunction>

The onSessionStart Method

Runs when your session starts.

<cffunction name="onSessionStart" returnType="void" output="false">
</cffunction>

This method is used for initialising SESSION-scoped data, such as a shopping basket and application form.

For example:

<cffunction name="onSessionStart" returnType="void" output="false">
	<cfscript>
	SESSION.start = now();
	SESSION.strShoppingBasket = structNew();
	SESSION.strShoppingBasket.items = 0;
	</cfscript>
</cffunction>

The onSessionEnd Method

Runs when session ends

<cffunction name="onSessionEnd" returnType="void" output="false">
	<cfargument name="sessionScope" type="struct" required="true" />
	<cfargument name="appScope" type="struct" required="false" />
</cffunction>

Use this method for any clean-up activities when the session ends. A session ends when the session is inactive for the session time-out period. You can, for example, save session-related data, such as shopping basket contents or whether the user has not completed an order, in a database, or do any other required processing based on the user’s status. You might also want to log the end of the session, or other session related information, to a file for diagnostic use.

Adobe Livedocs has a whole section dedicated to the Application.cfc.

I have created an example Application.cfc, which is available for download.