Flash Switcher Extension for Firefox

by Josh Tynjala

Alessandro posted a cool extension for Firefox that allows a developer to swap out different versions of the Adobe Flash Player without installers or browser restarts. It’s a great tool for testing player compatibility, and you’ll be able to see instantly if your Flash version-checking script works correctly. Best of all, it comes with every player all the way back to Flash 2! How’s that for overkill? ;)

After I installed the extension, I immediately added the Flash 9 debug player to the list. Until now, I specifically ran the release player on Firefox and the debug player in IE. I didn’t want to limit my performance when checking out the cool AS3 experiments everyone has been making. Now, I can easily switch to debug mode to catch bugs when I’m working on my own cool experiments.

By the way, if you’re looking for something a little more arcane (I always a found it little difficult to use), you might want to check out Flash Plugin Switcher. It works for both IE and Firefox.

A new direction for me, and Flex developers needed!

by Josh Tynjala

On December 4, I will be joining Flash Platform team at Yahoo! in Sunnyvale, CA. It should be an extremely exciting opportunity where I’ll get to influence the direction Yahoo! takes with Flash technology, and the team hopes to release some useful components and other code to benefit the whole Flash community. Stay tuned for more on that front.

As a result, my current employer, Business Objects needs a couple of talented Flex 2 developers ASAP to fill my shoes and further expand their component development team for Crystal Xcelsius in San Diego, CA. Xcelsius is a pretty cool application that lets business users create rich dashboards and presentations with Flash components, Excel spreadsheets, and other data sources. Ideally, you should be familiar with Adobe Flex 2, MXML, Actionscript 3, and you should have a strong understanding of the architecture behind the Flex framework and the creation of custom components. Please let me know if you’re interested in learning more about these positions.

MAX, CSS Reboot, etc.

by Josh Tynjala

I’ll be heading out for MAX in a couple hours. It’s my first MAX and my first trip to Vegas. In other words, a kick-ass good time! I’ll be at a bunch of Flex, Apollo, and other random sessions, so be on the lookout for me. Brown hair, black plastic glasses, and I’ll have my IFBIN-branded bag at my side. You may see me hanging out with with Flash rockstars like Jesse Warden or at the MAXUP unconference put together by Ted Patrick. Maybe you’ll catch me developing a cool project in some dark corner.

In other news, what’s up with the CSS Reboot? It has had virtually zero content for some time now, and the rebooters page gives a nice MySQL error. I’m unimpressed. I didn’t finish a new design for my blog, so it doesn’t bother me too much. Today, I found the Standards Reboot website. It seems to have some decent sponsors, so check it out if you want to reboot on November 1st. I have a lot of cool ideas to spruce up this old place, but I just didn’t have time to put them all together. I’ve barely found time to try out my new Nintendo DS because my day job, a little freelancing, and other top secret projects have kept my free time near zero.

Note to self: Write funnier code.

by Josh Tynjala

Google Code Search is pretty cool. Certainly, you’ll discover some oddities and troubling security issues, but I imagine that this might be helpful to a lot of folks looking for some quick fixes. I like that results will show the type of license if Google’s crawler can find it.

A funny query that someone on Slashdot pointed out makes me want to refactor some of my Actionscript code:

private static const POPE_IS_CATHOLIC:Boolean = true;

public function doSomething():void
{
	while(POPE_IS_CATHOLIC)
	{
		//do something
	}
}

It will be interesting to see if this and other code search engines help to discover GPL and other license violations. Obviously the code has to be accessible to the public for the crawler to find it, but I imagine that it’s still a useful tool in that realm.

Flex 2 UITextFields don't allow percentage dimensions

by Josh Tynjala

FYI, the documentation doesn’t say anything about it, but the percentWidth and percentHeight properties don’t work on UITextField instances in Flex 2. Here’s the spartan implementation of the percentWidth property:

/**
 *  @copy mx.core.UIComponent#percentWidth
 */
public function get percentWidth():Number
{
	return NaN;
}

/**
 *  @private
 */
public function set percentWidth(value:Number):void
{
}

The documentation states that these properties may be set to values from 0 to 100. I’ve submitted a bug report, but I thought I’d send out a warning.

I guess it’s time for a little subclassing. I’ve been having a lot of frustration with text-based components in Flex. Labels can only be a single line. UITextField seems to be the best bet for multiline text because the Text component is a horrible pain in the rear that doesn’t seem to like word-wrapping. Flex team developers, if you’re listening, I want better text-based components!

More Fun with Flash 9 Particle Systems

by Josh Tynjala

Back in May, I spent some time experimenting with particle systems in Flash 9 and Actionscript 3. Thankfully, I found some time to come back to this project. I had one goal in mind: The concept of a particle system must be as flexible as possible. It could be anything from the flames and steam I created in my previous project to falling snow or even something more complex that involves artificial intelligence and flocking behaviors.

Let’s take a look at a couple of the different particle systems that I’ve created. You can see that flames made a comeback in the example below. To mix things up, I used several active particle systems at once, and I threw in a video game sprite to add some flavor. It may be a little heavy on the CPU, but as you can see, a particle system (or six, in this case) can add a lot of atmosphere to a scene.

Preview image of flames particle effect

Next, I created a fountain of spraying water. The water fades from blue to white and an occasional drop flies high above the others. You’ll see that the individual particles are a little more obvious in this example, but I think I was able to give the water some personality to make up for it.

Preview image of a fountain particle effect

Finally, I wanted to create a system that featured “skinned” particles. The snowstorm that I linked to above inspired me to create an example with falling leaves. I imported vector art from Flash to represent each particle, and as you move your mouse left and right, you control the direction of the wind. I created the illusion of depth by making smaller leaves fall slower to make them appear further away from the viewer.

Preview image of a flying leaves particle effect

Not quite as impressive, though technically interesting, I also made a swarming effect using animation along Bezier curves, and I started work on a simple bitmap particle system. I’d like to spend some more time on this project because I’ve got a bunch of cool ideas, but I have to move on to other things for now. Expect me to post random cool effects from time to time.

Full source code is available under an MIT license, and I’ve included ASDoc documentation. If you decide to play around with the code at all, I’d love to see what you create!

Update (08/06/2008): For completeness sake, I’ve included two classes below, ColorUtil and PointUtil, that I reference in the examples, but I omitted from the download:

ColorUtil.as

////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007 Josh Tynjala
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package zeuslabs.utils
{
	public class ColorUtil
	{
		public static function blendColors(color1:Number, color2:Number, percent:Number = 0.5):Number
		{
			var remaining:Number = 1 - percent;

			var color1RGB:Object = ColorUtil.hexToRgb(color1);
			color1 = ColorUtil.rgbToHex(color1RGB.red * percent, color1RGB.green * percent, color1RGB.blue * percent);

			var color2RGB:Object = ColorUtil.hexToRgb(color2);
			color2 = ColorUtil.rgbToHex(color2RGB.red * remaining, color2RGB.green * remaining, color2RGB.blue * remaining);

			return color1 + color2;
		}

		public static function hexToRgb(color:Number):Object
		{
			var rgbColor:Object = {};
			rgbColor.red = (color & 0xff0000) >> 16;
			rgbColor.green = (color & 0x00ff00) >> 8;
			rgbColor.blue = color & 0x0000ff;
			return rgbColor;
		}

		public static function rgbToHex(red:uint, green:uint, blue:uint):Number
		{
			return (red << 16) + (green << 8) + blue;
		}
	}
}

PointUtil.as

////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007 Josh Tynjala
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package zeuslabs.utils
{
	import flash.geom.Point;

	public class PointUtil
	{
		public static function reverse(v:Point):Point
		{
			return new Point(-v.x, -v.y);
		}

		public static function scalarMultiply(v:Point, s:Number):Point
		{
			return new Point(v.x * s, v.y * s);
		}

		public static function scalarDivide(v:Point, s:Number):Point
		{
			return new Point(v.x / s, v.y / s);
		}

		public static function dotProduct(u:Point, v:Point):Number
		{
			return (u.x * v.x) + (u.y * v.y);
		}

		public static function rotate(u:Point, angleRadians:Number):Point
		{
			var v:Point = new Point();
			v.x = u.x * Math.cos(angleRadians) + u.y * Math.sin(angleRadians);
			v.y = -u.x * Math.sin(angleRadians) + u.y * Math.cos(angleRadians);
			return v;
		}

		public static function rotateToPoint(origin:Point, target:Point):Number
		{
			var dx:Number = target.x - origin.x;
			var dy:Number = target.y - origin.y;
			return Math.atan2(dy, dx) * 180 / Math.PI;
		}

		public static function distance(p1:Point, p2:Point):Number
		{
			var dx:Number = p2.x - p1.x;
			var dy:Number = p2.y - p1.y;
			return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
		}
	}
}

Object-Oriented Actionscript for Flash 8 overflows with knowledge (Part 2)

by Josh Tynjala

If you’re looking for the ultimate book on Actionscript 2 programming, Object-Oriented Actionscript for Flash 8 should be your first choice. The book comes in at 540 pages, and holds so much knowledge that I needed to break my review into two parts. Before leaping into my thoughts on the second half, don’t forget to take a look at my previous examination.

In the second half, Peter Elst and Todd Yard take a quick look at the MX Components Framework that comes with Flash, and they use the knowledge from the first part of the book to build their own framework. Chapter 14 outlines the core classes of the MX Framework, specifically MovieClip (from the native Flash classes), UIObject, UIComponent and View. This chapter mainly offers an introduction to the idea of a framework, and you’ll later discover that the authors take some ideas from these base classes to use in their own design choices.

Elst and Yard start implementing some sound and style management classes in the next chapter. The goals for this framework aren’t quite as generic as say, Adobe’s Flex Framework, so the StyleFormat utility class that goes with StyleManager has some specific properties for things like borders, shadows, and fonts. Since these properties might not apply to every component, I don’t think I’d build it like that for my own projects. However, I think that it works well as a teaching aid to help the reader visualize the purpose of the class easier. Of course, I remember a post from Jesse Warden where he considered the need for a super-flexible framework for Flash projects with ultra-short deadlines. Ideally, such a framework would exist to solve common problems, but it would need to be enormously customizable to accomodate designers. For a project like that, simple design parameters like the ones used in the example might be a good way to speed up development.

Chapter 16 lays the groundwork for user interface components. Like Flash’s MX Framework, a UIObject class provides a common interface for use with all visual components. On the next layer, the authors implement a Block class which can be used with graphical assets. For instance, one Block might be used to skin a button component. Finally, they hope to finish up with a SimpleButton component. This chapter is one of the largest in the book and it contains a good deal of information, including integration with styles, graphics, events, states, and sounds. If you’re planning on creating reusable components, I recommend studying this section a bit to help yourself understand their methods. Even if you don’t use their base classes, the process of component development should be beneficial. It’s quite common in the Flash world to build your own components from scratch. Over the lifetime of Flash, many have developers have discovered that no magic bullet exists in this area. You have to balance flexibility, file size, performance, and more.

With a component system in place, the authors dive into animations. I found this chapter very interesting because it included many examples of using inheritance versus composition. With inheritance, a subclass takes the properties and methods from its parent class. For example, a Volkswagon “is a” Car. On the other hand, composition means that a class contains an instance of another class. A Car “has a(n)” Engine. We start out by creating a base Animator class. Two more classes, Tweener and Mover inherit from Animator. Mover, interestingly enough, uses a Tweener to handle its animation. From an OOP perspective, this design re-enforces the concept of encapsulation covered in earlier chapters, and you might not even notice that it’s happening.

In Chapter 18, “Interrelationships and Interactions Between Components”, the authors look into data binding, formatting, and validating. Unlike previous chapters, where they developed their own framework solutions from scratch, they’re now using some of the classes that come with Flash out of the box. This sort of confused me a bit. It took me a little while to realize that they had finished with the framework development, and they had moved on to the section about “Data Integration”. The section also includes browser interaction through Flash’s ExternalInterface and interaction with the server through XML and web services. It’s all very useful information that every Flash developer should know about, but I feel like this section would fit better in a more general Flash book. The rest of the book has been about learning good OOP design skills. Certainly, a good skill is knowing that you shouldn’t reinvent the wheel, but I felt like the natural progression broke during the transition to this section.

The book finally reaches its end with another case study. This time, the authors build a timesheet application. You’ll see a little UML again as the authors design the class structure. They’ll make use of the Model-View-Controller design pattern again. It’s a pretty complex little project, and you’ll want to study it, and probably recreate it in Flash to understand it well. You should pick up some good nuggets of information, and its always useful to see how others develop their projects.

I’ll admit, my love for the second half isn’t as strong as the first, but that’s a little more about the presentation style than the actual content. Whatever your skill level, I believe you’ll find some great information in Object-Oriented Actionscript for Flash 8. If you’re a Flash beginner, or you’re looking to move from the timeline into proper classes, you should have bought the book yesterday. Seriously, you won’t find a better text to help you with your transition. If you’re more advanced, you’ll find that this book is an enjoyable read that might give you some new ideas. I’ve added it to my official recommendations. As a final note, don’t let it discourage you that Actionscript 3 and Flash 9 projects might be around the corner. Focus on the object-oriented parts because it doesn’t matter what langauge you use. Good design is universal.

Object-Oriented Actionscript for Flash 8 overflows with knowledge

by Josh Tynjala

When I picked up Object-Oriented Actionscript for Flash 8, I kept my expectations neutral. I’ve said it before, but it’s important to note, I hate programming books. They’re either too dry or too basic. Thankfully, Peter Elst and Todd Yard kept things interesting in early chapters, and their writing flowed smoothly to help keep me interested as they added on each new layer of information. Coming in at 540 pages, this mighty tome is one of the thickest Flash books on my bookshelf. I don’t own the printed version of the Actionscript 2 Language Reference myself, but it might be the only one that’s bigger.

The first chapter, “Introduction to OOP“, contains the best explanation of objects and classes that I’ve heard yet. If you’re thinking that it’s time to move on from timeline code to classes, this chapter alone should help the most in getting you started. The writers keep it short and sweet, yet these eight pages contain many great diagrams and analogies to ease you into core concepts including encapsulation, inheritance, and polymorphism. It’s so simple to visualize things like a blueprint (class) being used to create a house (object), or the fact that cars from two different companies, such as Volkswagen and Toyota, can both be started by turning a key (inheritance and interfaces). To keep the reader in a programming mindset, a few lines of pseudo-code help to reinforce each new concept.

In the next couple of chapters, the authors introduce basic programming concepts and the Actionscript 2 language. This section goes by very quickly, and if you’re just getting started, you might want to read it over a couple of times. It seems to me that the authors pretty much assume that you’ve already done a bit of programming and you’re really looking to move on to the next. If you’re coming from a different language, like Java, it’s perfect because you can easily skim to each example of syntax. I like that a lot. Everytime I pick up a book to learn a new language, I hate reading through half a dozen chapters that assume that I’ve never heard of a compiler or a variable.

Chapter 4 presents ways to plan a programming project. The reader learns about different projects phases and how to use UML to represent classes and their relationships. Chapter 5 introduces workflow tools like version control systems (like CVS or Subversion), programming appearches like RAD and Extreme Programming, and a short section on usability. The final chapter in this section goes over some of the authors’ personal best practices. They present different ways to format code, reasons for using comments, and good naming schemes for variables and functions.

With the basics out of the way, the authors begin showing real Actionscript examples of those core programming concepts covered in the first chapter. We start out with some basic encapsulation that seperates different actions into functions. As the first bit of real code, the example of a ball moving on the stage is represented in timeline code. Personally, I would have liked to see the authors just move straight into classes, but this example is a good way to get a beginner started and to keep things familiar for Flash users that are already used to the timeline.

With the ball now rolling (bad pun), the authors start implementing their first classes. Like functions, classes offer another way to encapsulate functionality. Additional parts of classes like constructors, member variables and methods give the reader his or her first taste of what’s in store. Again, examples with real-world objects, like cars, help illustrate how classes work. The “Mover” class at the end of this chapter brings the earlier ball example into the modern Flash world, and it lays the groundwork for additional expansion in the next couple of chapters. With Mover implemented, the authors tackle inheritance by creating a Bouncer class with specialized functionality and a Gravity class to help reinforce the idea.

A short chapter on polymorphism goes on a bit of a tangent. Elst and Yard move away from the Mover classes, and polymorphism is presented differently. First, the basics are explained using body states such as hunger, boredom, and tiredness. It’s interesting to see the idea of interfaces shown without them actually being introduced yet. That happens in the next chapter. I almost wonder if perhaps these examples should have been used earlier. The reader may consider it a nice break from the coding, or it may be confusing. I can’t accurately judge that since I’m already well versed in this concept. When interfaces are truly introduced, we jump back into the Mover project and implement IMovable, IBounceable, and IGravity. With the previous movement classes, the code changes very little to include the interfaces. I always have trouble with chapters on interfaces. I believe that many seasoned programmers don’t always know when interfaces are needed, and I wish programming books would show better use-cases. It’s not specific to this book, just something that I’d like to see in more OOP books and tutorials.

The authors near the end of the first half with their introduction to design patterns. Patterns offer great, tested solutions to programming problems. They’re like frameworks that help you build your projects quicker, and they help you and others maintain your code more easily. Personally, I’m still learning patterns, so I found this chapter especially useful. Unfortunately, if you’ve already learned a bit about common patterns used by Flash developers, such as MVC, Singletons, Decorators, and Observer, you might not pick up much addtional knowledge. I could be wrong, but I believe that Colin Moock’s Essential Actionscript 2.0 covers the exact same patterns. Many folks highly recommend that book, so if you have trouble with this section, consider picking it up to hear a different author’s perspective on the subject.

The first half draws to a close with a case study that uses all of the techniques covered in earlier chapters. The authors create an OOP-based Media Player that can load Flash SWFs, Video, and MP3 files. By combining design patterns, some of the classes created earlier, and all sorts of great new examples of classes and inheritance, the authors do a wonderful job of bringing everything full-circle. There’s a good deal of code presented in this chapter, but each section includes a specific explanation. If you’re just learning these concepts, I highly recommend running through this whole example in Flash to get it working. The best way to learn is to just jump in and do it.

In any other Actionscript book, I’d expect to have reached the end. However, Peter Elst and Todd Yard truly go the extra mile. The first half is mainly geared toward AS2 beginners, but the second half bursts with knowedge aimed at more advanced developers. Stay tuned for part two of my review on Object-Oriented Actionscript for Flash 8 where the authors create a framework and present chapters on some of Flash’s included classes and features that you may not even know about.

Flex 2 Containers and the "parent" Property

by Josh Tynjala

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

by Josh Tynjala

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.

Pages: Prev 1 2 3 ...11 12 13 14 15 16 17 18 19 20 21 Next