A simple MXML Component; Toggletxt

I’ve written Toggletxt to demonstrate how easy it is to create components in Flex.

Toggletxt uses a Text component and enables users to toggle it’s visibility when clicked. Toggletxt offers very little extra functionality to the Text component but is a nice way of demonstrating MXML-based component creation. It could arguably be developed as a pure Actionscript component that is a subclass of the Text class but I’ll use it to demonstrate the MXML component paradigm instead .

What is an MXML component?

Simply put, it is an Actionscript component with an added layer of abstraction in the sense that you don’t need to write the actual Actionscript code that sets up the structure of the class. Instead, you can work with the mark-up syntax of MXML and add any necessary code in script blocks and/or include files. It will be converted to a pure Actionscript class when the Flex application is compiled.

Create a namespace.

One of the benefits of using components is that it allows us to organise re-usable pieces of functionality by placing them in folders. We can to refer to a component that resides in the folder through the use of a namespace. I have placed the Toggletxt component inside a folder called ‘comp’ and I refer to it in my application file by defining a namespace (also called ‘comp’ but doesn’t have to be the same) in the Application node:

So far the component doesn’t offer anything more than what the standard Text component. Now I’ll add the Actionscript that toggles the view of ‘txtOb’.

A little bit of Actionscript.

I have written a function called ‘toggleTxTView()’ that is called when a user clicks an instance of ‘txtOb’. (Don’t forget to assign this to ‘txtOb’s’ click event.) This will result in a rectangle called ‘myRect’ being added to the DisplayList directly above the ‘txtOb’ instance:

This also adds a MOUSE_DOWN event listener to ‘myRect’ that will call another function called ‘toggleMe()’ when the LMB (left mouse button) is pressed over ‘myRect’. It’s also a nice example of how the DisplayList works in AS3: