Beginning Flex: Creating your first custom event

Welcome to the first "real" article in my burgeoning "Beginning Flex" series. Today we're going to talk about creating custom events. As you may know, Flex is based on Actionscript 3 an object oriented, event driven, language. What are events you ask? Events are things which trigger actions. Your mouse hovering over this line of text causes the cursor to turn into a little I-bar. Clicking on a button in my navigation fires an event which loads a new page. Flex offers a wide range of events, from mouse triggered events, keyboard events, click events, they're all represented. In many cases the built in events are just what you need.

But sometimes, you want a little something more. You need to send a piece, or a whole packet, of data along with your event. Maybe you just want other developers to know that something special is happening in your code, who knows. The point is that not only does Flex offer those nice built-in events, but it also allows you to create your own. This article will show you how.

Before we get started, let's take a look at the result of the work we're about to do.

picture of directory structure Start by creating a new Flex project, alternately you can download the files for this article as a Flex Builder project and import it. For this one, I've named the project CustomEvents. There's also never a better time to organize your code, so I'll also create an events folder, and a components folder (as you can see to the right). We'll also have the Class file for the event, as well as a single component file containing the Button. I've tried to comment the files thoroughly so that it makes more sense. If you've got questions, please feel free to ask them in the comments. In addition to downloading the Flex project, you can also pull the old "right click to view source" trick on the Flex movie itself.