Monthly Archives: August 2006

Flex 2 Containers and the "parent" Property

Did you know that children of a Flex Container may actually be its grandchildren? Containers in Flex have a property called contentPane that is of type mx.core.FlexSprite. If certain conditions are met, such as when the container needs scrollbars, new components may actually get added to this contentPane instead.

I discovered this behavior when I noticed that some components inside a Canvas container were behaving differently than the rest. The typically stopped drawing some of their children or they wouldn’t draw at the correct size. Normally, this wouldn’t happen, but I had quite a bit of code manipulating the display list to improve performance, and I kept running into issues when I used containers. Each child of the Canvas seemed to think that the Canvas was it’s parent, but I wasn’t so sure. I dug into the framework source code, and I discovered a hidden gem in UIComponent:

mx_internal final function get $parent():DisplayObjectContainer

Since components may override the parent property, Adobe engineers added this $parent property just in case. I traced out the value, and that’s when I found contentPane. Adobe’s documentation says it best:

This property allows access to the Player’s native implementation of the ‘parent’ property, which can be useful since components can override ‘parent’ and thereby hide the native implementation. Note that this “base property” is final and cannot be overridden, so you can count on it to reflect what is happening at the player level.

In my project, I might add a child to the Canvas container when it isn’t actually on the display list. I’m guessing that certain initialization code, or maybe even some validation code, never runs when the contentPane is active under these conditions. I’ve started using a subclass of the regular UIComponent instead of a Canvas now, and it seems to work fine. File this under, “Random Stuff I’ll Probably Never Encounter, But Still Good to Know”.

Separating Layout from Style and Functionality

Some recent comments by a JavaScript developer made me consider Flex programming in a new light. Many web developers follow a best practice of always separating their content, styles, and scripts into distinct parts. An HTML document should contain only the structured content of the document. CSS and JavaScript files should be loaded from external sources. As a Flex developer, you have similar building blocks at your disposal. MXML contains the structure of your application, stylesheets modify the application’s appearance, and ActionScript 3 lets you interact with the application’s components. Style and Script elements can load their respective content from other sources when you compile your application. Certainly, Flex developers can benefit from the practice of separating these three parts.

Let’s start out by defining a very simple Flex application. It contains a Button component with blue text that traces some text to the console when a user clicks it with their mouse. Nothing special, but it should help us explore the possibilities.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
	<mx:Button label="Click Me!" click="trace('You clicked the button!');" color="#0000ff"/>
</mx:Application>

It’s only three lines of code, and that’s pretty cool. On the other hand, everything appears all mixed together in the MXML. There’s nothing wrong with that code, but let’s explore some possibilities for separation. Consider this more complex version that puts the ActionScript and a styles into their own tags.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
	<mx:Button label="Click Me!" click="clickHandler(event)"/>

	<mx:Script>
		import flash.events.MouseEvent;

		private function clickHandler(event:MouseEvent):void
		{
			trace("You clicked the button!");
		}
	</mx:Script>

	<mx:Style>
		Button {color: #0000ff;}
	</mx:Style>
</mx:Application>

The majority of MXML files in complex Flex applications will probably look like that. Events will be sent to ActionScript functions and styles will all be defined in one central location. These two items could easily be loaded from external files:

<mx:Script source="myApplicationCode.as"/>
<mx:Style source="myApplicationStyles.css"/>

Surely, that’s separation nirvana… or is it? 😉

The JavaScript developer that I spoke with wondered why you need to call an ActionScript function within the MXML when listening for the click event. That’s a bad thing to do when working with HTML. Visitors with browsers that don’t have JavaScript, or users that turn it off, have trouble when a webpage calls JavaScript functions directly in hyperlinks. Can Flex achieve a stronger separation? Yes, actually it can. Should it? Probably not, but it’s a fun exercise. Consider the following revisions:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
	<mx:Button id="myButton" label="Click Me!"/>

	<mx:Script>
		import flash.events.MouseEvent;

		override protected function initializationComplete():void
		{
			super.initializationComplete();
			this.myButton.addEventListener(MouseEvent.CLICK, clickHandler);
		}

		private function buttonClickHandler(event:MouseEvent):void
		{
			trace("You clicked the button!");
		}
	</mx:Script>

	<mx:Style>
		Button {color: #0000ff;}
	</mx:Style>
</mx:Application>

As you can see, we’ve overridden the initializationComplete function to listen for the button’s click event. Now, every line of ActionScript appears inside the Script element. Pretty cool, don’t you think?

Remember, I’m not advocating that everyone go to these lengths to keep scripting, style, and structure apart. It’s far more important in the JavaScript world, but I believe that any developer can learn and grow by studying how other programmers do things–especially those that use different languages. You also shouldn’t over-architect your applications. I’d say that the first example with three lines of code would be the right way to build the example, but such a simple example lets us explore interesting concepts without needing to think about what the code is meant to do.

Flex 2 featured on SitePoint

For the next couple of weeks, SitePoint will be featuring an article I wrote about Flex 2. It’s titled Flex 2: Rich Internet Applications in a Flash!, and it gives an excellent birds-eye view of Flex and Flex Builder. According to Alexa, SitePoint ranks in the top 500 websites on the Internet. In other words, this article pushes Flex into the minds of a very large audience.

Recently, Ryan Stewart pondered why more people don’t know about RIAs. You could say the same thing specifically about Flex. Articles on high-traffic websites like SitePoint need to show how easy, but powerful, MXML and Actionscript 3 can be. Many developers consider Actionscript as nothing more than kids stuff. Sadly, JavaScript, which is based on the same standard, gets more interest thanks to the recent AJAX push. Strong examples, perhaps even pointing out the parallels between MXML/AS3 and HTML/JavaScript, should help the development community reconsider Flash as a great option.

Search Google in Flex 2

Important: The Google SOAP Search API is deprecated. You may not be able to use the source code for this project anymore! Check out the Google Search REST API for a replacement API to Google’s search results. The documentation includes examples in ActionScript 3 for using the JSON returned from this new API.

In my early days of learning Flash, I put together a cool little demo that used Google’s Search API. The SWF is lost somewhere in the depths of my hard drive, but I remembered it the other day when I spent some time brainstorming my next cool Flex 2 experiment. Thanks to Flex’s robust framework, and my improved Flash-fu skills, I implemented a working Google search component pretty quickly. As a result, I spent some extra time on layout and styles. You’ll notice the distinctive Google simplicity.

Before you check out my Flex 2 Google Search experiment, take note that a Google API key only allows 1,000 searches per day. If the demo doesn’t seem to be working for you, please bookmark this page so that you can come back to try it again tomorrow.

The main API implementation can be found in the GoogleSearchEngine class. By default, GoogleSearchEngine uses Flex’s HTTPService class to connect directly to Google’s SOAP service. In the future, Apollo applications should be able to use this functionality directly. For now, it’s important to note that Flash restricts cross-domain access to SWFs served from the web. To work around this restriction, I added the target parameter which takes an URL for some sort of proxy that can communicate between Flash and the web service. The live demo uses a nice little proxy written in PHP that I found at mattism.com. You’ll find it in the source code.

Originally, I intended to make the live demo send searches through an AJAX system. I used a slightly modified version of the Prototype library. Unfortunately, I discovered that Javascript has limited cross-domain access too. If you’re interested, AjaxExtended allows you to bypass this restriction. It overrides the browser’s regular XmlHttpRequest object to route the messages through a PHP script. Sounds familiar, doesn’t it? In the end, I figured it would be pointless to go through the AJAX subsystem, and I made the Flex application speak to the proxy directly.

Source code is available for download. You are free to use and distribute it under the terms of an MIT-style license. Certainly, there’s no reason why you or I couldn’t use the interfaces I created to build a similar system for Yahoo’s Search API. Does anyone know if other search engines provide a public API?

Get your hands on tons of FREE Flash and Flex code!

You may have seen the “IFBIN Author/Partner” badges that a few of us Flash bloggers have on our sites. If you’re not familiar, IFBIN offers hundreds of well-documented examples for Flash and Flex. All the examples are written by industry professionals, like Ted Patrick, Jesse Warden, Keith Peters, and Darron Schall (to name only a few). Until now, IFBIN code could only be obtained through a yearly subscription. Today, IFBIN is free and open source!

Download the IFBIN client, and check things out. All the source code is released under a BSD License. That means you can use this code virtually anywhere. Take a look through the examples and you might just find some code that will help you on a project right now.

Expect more great stuff in the future too. Ted is working on a new IFBIN client program written for Apollo. I imagine it will be one of the first definitive Apollo applications that really shines. We have plans to support examples for other Adobe products too. I can’t wait to learn some new Photoshop techniques. Finally, we want everyone to be able to submit examples. We’ll strive for the highest-quality and it should be great for everyone. Happy coding!