Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Showing posts with label actionscript. Show all posts
Showing posts with label actionscript. Show all posts

Thursday, November 6, 2008

Creating an ItemRenderer in ActionScript

I'm posting this for my benefit as much as anyone else. Here is a very basic ItemRenderer done in ActionScript. Something you might come across when building Flex/Air applications is errand problems with ItemRenderer's not performing as expected, sucking up lots of memory, or throwing errors. Many times these problems can be solved by building your renderer in ActionScript. Here is the source for a basic item renderer which can be scaled up as needed.

package my.renderer
{
 import my.model.DataModel;
 
 import mx.controls.Label;
 import mx.controls.listClasses.IListItemRenderer;
 import mx.controls.listClasses.ListBase;
 import mx.core.UIComponent;
 
 public class ArtListRenderer extends UIComponent implements IListItemRenderer
 {
  public function ArtListRenderer()
  {
   super();
  }
  
  
     [Bindable] public var myData:DataModel = new DataModel();
  
     // Internal variable for the property value.
     private var _data:Object;
     
     // Make the data property bindable.
     [Bindable("dataChange")]
     
     // Define the getter method.
     public function get data():Object {
         return _data;
     }
     
     // Define the setter method, and dispatch an event when the property
     // changes to support data binding.
     public function set data(value:Object):void {
         _data = value;
         
         myData = new DataModel();
         myData.firstname = value.firstname;
         myData.lastname = value.lastname;
                 
         invalidateProperties();
         dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
     }
     
     private var hBox:HBox;
     private var firstnameLabel:Label;
     private var lastnameLabel:Label;
     
     override protected function createChildren():void
     {
      super.createChildren();
      
      hBox = new HBox();
      
      firstnameLabel = new Label();
      lastnameLabel = new Label();
      hBox.addChild( firstnameLabel );
      hBox.addChild( lastnameLabel );
      
     }  
     
     override protected function commitProperties():void
     {
      super.commitProperties();
      
      hBox.horizontalScrollPolicy = 'off';
      hBox.verticalScrollPolicy = 'off';
      
      hBox.percentWidth = 100;
      
      firstnameLabel.text = myData.firstname;
      lastnameLabel.text = myData.lastname;
     }
     
     override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
     {
      super.updateDisplayList(unscaledWidth,unscaledHeight);
      hBox.move(0,0);
      hBox.setActualSize( (unscaledWidth-4), unscaledHeight);
     }
 }
}

Friday, October 3, 2008

Force creation of complete ViewStack with creationPolicy when building a form across multiple views : Flex Tip

Here's a tip which might be useful for some people.  Sometimes when building a Flex/Adobe Air interface you may want to have form elements which are built across multiple views of a ViewStack, or TabNavigator.  For example I have a contact form which has some rarely used fields contained in a secondary Tab in my form.

Problem with this approach is that the default value of a Container's creationPolicy is 'auto'.  This means child components are only created when they are needed.  If your user never looks at the extra tabs/view stack layers then these form elements are not available if you need to get values or set values for them.

The Solution is to simple set the creationPolicy for your ViewStack or TabNavigator to 'all'.  This will ensure that all child elements are created up front and are available when needed regardless if the user looks at them or not.

Thursday, October 2, 2008

Flex Tip : Use ObjectUtil for Alpha and Numeric sorting on a DataGrid

If you haven't taken the time to look at the features of Flex's ObjectUtil you should. Inside are a few handy methods which I see getting over looked.

Two of those methods are ObjectUtil.stringCompare and ObjectUtil.numericCompare. These methods make it simple to provide intelegent sorting on DataGrid columns.

Let's say you have a DataGrid that has one column full of ID# and another column full of people's names including both first and last names. Chances are the default sorting abilities of the DataGrid will not properly sort either column. The ID# would be sorted 1,10,11,12... instead of 1,2,3,4,5... and the column of names would sort by the first name and not the last name.

Lucky the DataGridColumn allows you to set a custom sort function via the property sortCompareFunction. For example look at these two DataGridColumns.

<mx:DataGridColumn headerText="ID#" dataField="contactid" sortCompareFunction="sortContactId"/>
<mx:DataGridColumn headerText="Name" dataField="full_name" sortCompareFunction="sortLastName">
 <mx:itemRenderer>
  <mx:Component>
    <mx:Label paddingLeft="5" text="{data.firstname} {data.lastname}" />
  </mx:Component>
 </mx:itemRenderer>
</mx:DataGridGolumn>

The first column is for the ID# of a contact, the second column uses an itemRenderer and displays both the firstname and lastname for the contact. Each column defines it's own sortCompareFunction. Both functions make use of methods from mx.utils.ObjectUtil.

private function sortLastName(obj1:Object,obj2:Object):int
{
   var value1:String = (obj1.lastname == '' || obj1.lastname == null) ? null : new String(obj1.lastname);
   var value2:String = (obj2.lastname == '' || obj2.lastname == null) ? null : new String(obj2.lastname);
   return ObjectUtil.stringCompare( value1, value2, true );
}
private function sortContactId(obj1:Object,obj2:Object):int
{
   var value1:Number = (obj1.contactid == '' || obj1.contactid == null) ? null : new Number(obj1.contactid);
   var value2:Number = (obj2.contactid == '' || obj2.contactid == null) ? null : new Number(obj2.contactid);
   return ObjectUtil.numericCompare( value1, value2 );
}

These functions are pretty straight forward.  sortLastName function uses stringCompare method to compare the lastname from two objects. The flag 'true' is set to make sure that the comparison is case insensitive. The sortContactId function uses the numericCompare method to compare the contactid from two objects.

Thursday, June 26, 2008

Flex Component : Yet Another Flex File Upload Component

There are several Flex upload components floating around and I gave most of them a good look over but I was not able to find one which suited my needs so I decided to make my own. Here it is for you to enjoy.

Click here to view a demo
(demo lets you upload up to 3 files at a time with a max size of 4 megs each)

Click here to view the source

The usage of the component is pretty straight forward. You can set some properties to define what types of files can be uploaded and you direct the 'upload' towards a server side script. In my demo I send the files to a basic PHP script ( which I've included below ). The script handles one file at a time and is expected to report back either the string 'successful' or an error message which is displayed.

Properties

The following public properties can be set to customize the use of this component

  • uploadButtonLabel : String = 'Upload'
    This is the label used for the 'upload' button.

  • selectButtonLabel : String = 'Select File(s)'
    This is the label used for the 'select' button.

  • removeButtonLabel : String = 'Remove Selected File'
    This is the label used for the 'remove' button.

  • maxFileCount : Number = 3
    This sets the number of files a user is allowed to upload

  • maxFileSize : Number = 1
    This sets the maximum file size (in megs) for each individual file. Default is 1 meg.

  • requestUrl : String = ''
    This is the URL for your PHP/ASP/ColdFusion/Other script which you will send the uploaded files to. THIS PROPERTY MUST BE SET !

  • allowOnlyImages : Boolean = false
    If set to 'true' the user will only be able to select image files

  • allowOnlyText : Boolean = false
    If set to 'true' the user will only be able to select text files.

  • allowAllFiles : Boolean = true
    If set to 'true' the user can upload images or text files.

  • barColor : String
    Allows you to style the progress bar
Events

The component has one event 'uploadComplete' which is triggered if all files are uploaded successfully.

The PHP Handler

Following is the source for the simple PHP script which I am using in the demo. In this script I am just confirming that the file was uploaded successfully and then I am deleting it. Since this is a public demo I don't want people filling up my server with unwanted images. In your script you would most likely copy the FILE to a more permanent location and possibly do a little more validation. The script needs to echo the string 'success' or echo an error message.
$hasError = false;
foreach( $_FILES as $i=>$file ){
if ( $file['error'] ){
$hasError = true;
}
/**
* Because this is a public example. I am just going to immediately delete
* the file which was uploaded. In a regular application you would copy the file
* from it's temporary location to it's permament location.
*/
unlink( $file['tmp_name'] );
}

if ( ! $hasError ){
echo('success');
} else {
echo('Stick custom error message here');
}

Tuesday, May 20, 2008

Multiple AutoComplete Input Controls in a single Flex Form

A very nice component which is available from Adobe is their AutoComplete ComboBox. The AutoComplete Combo box looks like a regular TextInput component but will provide suggestions to the user as they type. This is very handy when you want to let users select from a long list of options ( such as a list of Countries ).

Jen Krause has posted a modified version of the component which allows the user to press ENTER, TAB or click their mouse button to select the first selected item. This is a very nice modification.

A problem I ran into however was using multiple AutoComplete components in the same Flex form. If you try and put more than one AutoComplete component in the form, the first component looses the label of the selected item when you begin using the second component. I wasn't able to determine the cause of this problem but I was able to provide a simple work around.

If you've run into a same problem, you can fix it by making the following change to the class' focusOutHandler method.

// Change this method ...
override protected function focusOutHandler(event:FocusEvent):void
{
super.focusOutHandler(event)
if(keepLocalHistory && dataProvider.length==0)
addToLocalHistory();
}

// To this ....
override protected function focusOutHandler(event:FocusEvent):void
{
super.focusOutHandler(event)
if(keepLocalHistory && dataProvider.length==0)
addToLocalHistory();
_typedText = textInput.text; // replace typedText with textInput.text
}

I'm not sure if there are any ramifications to this fix but I haven't found any additional problems in my own application.

UPDATE
Turns out there are numberous implications when using multiple AutoComplete Input controls in the same form specifically when you want to try and set the value of the controls with actionscript. If you only need one AutoComplete input control then this component works really well and is very user friendly. However if you need multiple controls you may want to re-consider your form design choices.

Thursday, April 17, 2008

PHP explode() function in Actionscript for Flex

If you're a long time PHP programmer who has made the leap to building Flex based RIA applications in Flex you are probably asking yourself from time to time "how do I do a xxxxx function in actionscript". Well if you were recently wondering this about the PHP explode() function, here's your answer.

public function explode( delimiter:String, str:String ):Array
{
return str.split( delimiter );
}

warning: unable to bind to property 'XX' on class 'Object' (class is not an IEventDispatcher)

When working with data pulled in from an HTTPService in Flex you may find that at run time your application spits out a bunch of warnings that it is unable to bind to a property.

If you want to prevent these warnings from occuring you should process your the data for your in actionscript instead of MXML.

Change this ...

<mx:Label text="{myresults.dynamiclabel}"/>
To this ... ( calling the function init() with the creationComplete event )
<mx:Script>
[Bindable] private var dynamiclabel:String;
private function init():void
{
this.dynamiclabel = myresults.dynamiclabel;
}
</mx:Script>
<mx:Label text="{this.dynamiclabel}"/>
I know this approach requires a little bit more code and the first approach works, but this way it doesn't result in any warnings. I'll make the assumption that no run-time warnings means more compliant code.

Another approach to solving the problem is by wrapping Arrays in ArrayCollection and Objects in ObjectProxy wrappers. I got the following example from here.
function resultHandler(result:Array)
{
for(var i:String in result)
{result[i] = new ObjectProxy(result[i]);}
targetArrayCollection = new ArrayCollection(result);
}
What about using ItemRenderer(s)?

If you are combining the use of an ItemRenderer and data from an HTTPService in your application you may find that neither of the above solutions fully work. What you really need is a modification of the first solution. Collecting your data in response to the creationComplete event will only collect data when the itemRenderer is first created. The event is not called when dynamically change the dataProvider. An approach to solving this scenario is the create a ChangeWatcher in the ItemRenderer to respond to changes to the data property of said ItemRenderer.

<mx:Script>
import mx.binding.utils.ChangeWatcher;
import mx.events.PropertyChangeEvent;

private var dataWatcher:ChangeWatcher;

[Bindable] private var dynamiclabel:String;

// ** Call this function from creationComplete event **
private function init():void
{
this.dataWatcher = ChangeWatcher.watch( this, 'data', dataChangeHandler );
this.dataChangeHandler();
}

private function dataChangeHandler(event:Event=null):void
{
this.dynamiclabel = data.dynamiclabel;
}
</mx:Script>
<mx:Label text="{this.dynamiclabel}"/>

Saturday, April 5, 2008

Customizing the Flex ScrollBar with Skins

One of the things I love about Flex is the smooth and clean look/feel of the default components. With just a little CSS the default look and feel can be customized to fit most web site designs. But what do you do when your requirements are very different from what you can accomplish with CSS? With Flex it's possible to build custom skins and give you're application any look and feel you desire.

While the process to complete this isn't overly complex it probably helps if you come from a Flash background and also have some strong design skills.

There are two ways to build skins. 1) Use images and 2) Use actionscript classes. For my example I have combined both approaches to customize the look/feel of the default Flex scrollbar.

Summary of the solution

- Create a PNG image to use as the background for the scrollbar track.
- Create a PNG image to use as the icon for the scrollbar handle.
- Create an ActionScript class to draw a skin for the scrollbar box.
- Create a CSS Style for the scrollbar which references the new skins
- Apply the StyleName to our scrollbar

The CSS Style

.customScroll
{
/* remove the arrow skins by referencing a null class */
upArrowSkin: ClassReference(null);
downArrowSkin: ClassReference(null);

/* Embed an image to use as skin for scroll bar track and scroll bar thumbIcon */
trackSkin: Embed(source="skins/CustomSkinTrack.png");
thumbIcon: Embed(source="skins/CustomSkinIcon.png");

/* Reference action script skin for various states of the scroll bar thumb */
thumbUpSkin: ClassReference('theme.skins.CustomSkinThumb');
thumbOverSkin: ClassReference('theme.skins.CustomSkinThumb');
thumbDownSkin: ClassReference('theme.skins.CustomSkinThumb');
}


Click here to view the demo.
Click here to view the source code.

Monday, March 17, 2008

Flex SuperLabel Component : An Easy How To on Extending Flex Components with Custom Events and Effects

Since I switched from developing XUL/Javascript based RIAs using the Mozilla platform to programming in Flex and Actionscript one of the things I have been most impressed with is how easy it is to extend existing components and customize them to fit my needs perfectly.

Recently (as in 10 minutes ago) I was working on laying out the interface for a new application which displays some dynamically changing content. One part of the interface which was dynamically changing was the page title which I was displaying as a Label component. I thought it would be nice to add a small effect every time the text property for Label changed. Looking at the language reference documentation for the Label component I noticed there was no built in event or effect which could be triggered when the text property is updated.

No problem, I thought. I'll just add that in. So with less than 25 lines of code and in less time than it is taking to type this post I was done.

Here is a summary of the steps I took to create my new SuperLabel Component.

  • Created a new Actionscript Class
  • Added Metatags for the new Event and new Effect
  • Created a function which overrides the text property setter function
  • done.
Here is the source code for the new component.
package claire.com
{
import mx.controls.Label;
import flash.events.Event;

[Event(name="textChange", type="flash.events.Event")]
[Effect(name="textChangeEffect", event="textChange")]

public class SuperLabel extends Label
{
public function SuperLabel()
{
super();
}
public override function set text(value:String):void
{
if ( value != this.text )
{
this.dispatchEvent( new Event('textChange') );
}
super.text = value;
}
}
}
There you go. It really is that easy.

Just to finish off here is how you use the new component in MXML.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:com="claire.com.*">
<mx:WipeRight id="myEffect" duration="750" />
<com:SuperLabel textChangeEffect="{myEffect}"/>
</Application>

Wednesday, March 12, 2008

Flex Tip: Adding custom events to Actionscript components

One of the key features of building a Flex application with custom components is being able to define and dispatch custom events. In order to do this you need to add some metadata to your custom component.

If you're creating an actionscript class for your custom component you declare the metadata before defining your class as in the following example.

package claire.libs
{
....
[Event(name="serviceError", type="flash.events.Event")]
public class ClaireService extends HTTPService
{
.....
}
}

You will now be able to add an event listener in MXML with the following.
<mycom:ClaireService id="myService" serviceError="handlerFunction(event)"/>

While the above example works it is important to note that the following example will NOT work. Notice the ";" at the end of the Event metatag. Took me about 2 hours to figure this out so hopefully this post will save someone else some time.
package claire.libs
{
....
[Event(name="serviceError", type="flash.events.Event")];
public class ClaireService extends HTTPService
{
.....
}
}

Saturday, March 1, 2008

Display a time counter in flex

For my Sudoku game I wanted to add a simple counter which shows how much time has passed since a user started their game. Should be simple enough, just create a Timer object and have it update a display every second. The problem I ran into was how to easily display the number of seconds passed as a readable time format (example HH:MM:SS). I searched high and low for any type of formatting function which would help but came up short and had to figure out something on my own.

What I came up with feels like a total hack and I'm certain there has to be a better way to solve this problem. Anyway, here is my code, it appears to work just fine but would appreciate it if anyone knows of a better solution.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
// Create Timer object to fire every second with no end
private var myTimer:Timer = new Timer(1000);

private function init():void
{
// Add event listener for the time
myTimer.addEventListener(TimerEvent.TIMER,clockTick);
myTimer.start();
}
// function to update display
private function clockTick(event:TimerEvent):void
{
var fullseconds:Number = Timer( event.currentTarget ).currentCount;
var fullminutes:Number = Math.floor(fullseconds/60);
var hours:Number = Math.floor(fullseconds/3600);
var minutes:Number = ( hours > 1 ) ? Math.round((fullseconds-(hours*3600))/60) : Math.floor(fullseconds/60) ;
var seconds:Number = ( fullseconds > 60 ) ? fullseconds-(fullminutes*60) : fullseconds;
var hourstr:String = ( hours < 10 ) ? '0'+hours.toString() : hours.toString();
var minstr:String = ( minutes < 10 ) ? '0'+minutes.toString() : minutes.toString();
var secstr:String = ( seconds < 10 ) ? '0'+seconds.toString() : seconds.toString();
if ( minstr == '60' ) minstr = '00';
if ( secstr == '60' ) secstr = '00';
myClock.text = hourstr+':'+minstr+':'+secstr;
}
]]>
</mx:Script>
<mx:Label id="myClock" />
</mx:Application>

The one part which really bugs me about this is manually adding a '0' to numbers less than 10. If I was working in PHP this would be no problem but being a n00b with actionscript this is the best I could come up with in the hour I had to work on it.

Dynamically moving a Flex Component

When it takes me more than 4 or 5 searches on google to find a solution to a problem then for me it's worth blogging about. I'm either going to help someone else in the same situation or i'm going to highlight my ineptness a finding solutions.

At any rate I was recently trying to figure out why when moving a component around my application it would snap right back to it's original x/y coordinates. Turns out you can only move a component when it's parent container is a Canvas, Application or Panel with it's layout property set to 'absolute'.

So there you go. Happy flexing.

Binding in Flex with Getters and Setters

When building a component class and using the recommended method of providing access to properties with getter and setter functions you may find that you are unable to bind to these properties. It's actually rather trivial to enable binding but perhaps not overly obvious. All you need to do is add [Bindable] before the getter function.

 private var _myVar:String;

[Bindable] public function get myVar():String
{
return this._myVar;
}
public function set myVar( value:String ):void
{
this._myVar = value;
}

Thursday, February 21, 2008

PHP in_array() function in ActionScript for Flex

Another common PHP function is in_array() used to determine if a value exsists in an array. Here is the function recreated in actionscript for flex.

public function in_array( needle:*, haystack:Array ):Boolean
{
var itemIndex:int = haystack.indexOf( needle );
return ( itemIndex < 0 ) ? false : true;
}

Wednesday, February 20, 2008

Flex On Screen Qwerty Keyboard Component

NOTE:  I've updated this component. To see the latest version click here.

One of the Flex applications I work on is a touch screen application primarily used to browse a product catalog. Because there is no keyboard physically attached to the touch screen display and it was necessary to have some input from users (primarily for signing up to a mailing list) I built a Qwerty keyboard component for flex.

The component displays a nearly full set of keys found on your standard Qwerty keyboard with a limited set of special characters. You can assign TextInput and TextArea controls to accept the output from the component and there is a handy method for changing focus to different input fields.

Click here to view the example application

Click here to view source

Basic Usage

<mx:Form width="100%">
<mx:FormItem label="Field 1" width="100%">
<mx:TextInput id="field1" focusIn="myQwertyKeypad.newFocus(field1)" width="100%"/>
</mx:FormItem>
<mx:FormItem label="Field 2" width="100%">
<mx:TextInput id="field2" focusIn="myQwertyKeypad.newFocus(field2)" width="100%"/>
</mx:FormItem>
<mx:FormItem label="Field 3" width="100%">
<mx:TextInput id="field3" focusIn="myQwertyKeypad.newFocus(field3)" width="100%"/>
</mx:FormItem>
</mx:Form>
<claire:Qwerty id="myQwertyKeypad" inputControl="{field1}" width="100%"/>


While probably a pointless component for most Flex Applications this component is very handy for touch screen input requirements.

Flex FocusManager and Cursor control

Working on a component which needs to programatically set focus to a TextInput field and make sure that the cursor is placed at the end of current value. I found this possible by using both the Flex FocusManager and also the setSelection() method of TextInput. Figured the code snippit might be useful to other people so here it is.

//assuming myInputField is the id of a TextInput field
focusManager.setFocus(myInputField);
myInputField.setSelection(myInputField.length, myInputField.length);

Monday, February 18, 2008

PHP ucfirst() and ucwords() in Flex

Another common PHP function converted to ActionScript for use in a Flex application.

public function ucfirst( str:String ):String
{
return str.substr(0,1).toUpperCase()+str.substr(1);
}
public function ucwords( str:String ):String
{
var myArr:Array = str.split(' ');
for (var i:int in myArr ) {
myArr[i] = ucfirst( myArr[i] );
}
return myArr.join(' ');
}

PHP strtoupper() and strtolower() in Flex

Having been a PHP programmer for many years and only now in the last month started to learn Flex and ActionScript I find I'm always looking for ways to get something done in ActionScript which I know how to do in PHP. These are pretty straight forward and simple functions but sometimes it's nice to have a reference.

PHP strtoupper( $string ) and strtolower( $string ) in Flex

public function strtoupper( str:String ):void
{
return str.toUpperCase();
}
public function strtolower( str:String ):void
{
return str.toLowerCase();
}

Sunday, February 17, 2008

Flex / JSON / PHP Example Application

While trying to teach myself how to best use PHP and Flex together I build the following example application. Source code and details on how the application works are included.

The example application uses JSON (JavaScript Object Notation) to facilitate a smooth and simple way of providing PHP Arrays that can be used by a Flex Application. A more complete HowTo is included in the application.

Click here to launch the application
(right click to view source)

Requirements

This application requires a php class called json.php which encodes a PHP array and the corelib libraries available from Adobe Labs used to decode the array in Flex. You'll also need a mysql database with a single table called 'people' with the fields 'firstname','lastname' and 'category'.

To install the corelib libraries I used a post at Mike Chambers blog.
The json.php class originally comes from M. Migurski.

MXML Summary

Right click the example application to view the MXML source

  • FlexPhp.mxml : Main Application file. Contains a navigation tab and loads the components PhpDataGrid.mxml and PhpForm.mxml
  • PhpDataGrid.mxml : Contains a simple DataGrid and ActionScript for calling read.php
  • PhpForm.mxml : Contains a simple Flex form and ActionScript for calling write.php
Description of PHP Files

read.php : File queries the database and returns a JSON encoded array to the Flex application.
write.php : File accepts data posted from Flex form, updates the database and sends a JSON encoded response back to the flex application.
json.php : Class file used to encode PHP arrays into a JSON formatted string.
mysql.php : Class file for accessing and updating the database.
conf.php : Simple configuration file for keeping database access information and debugging.


Thursday, February 14, 2008

Auto Reloading a Flex Application

I have a flex application which runs on a touch screen and I want to have the application reset itself when no one is using it.

To get this done I created a Timer that would reload my Flex app every 5 minutes and an event listener which would reset the timer everytime someone touched the screen (or clicked the app).

Example below.

AppTimer.as ActionScript Class File


package
{
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.net.URLRequest;
import flash.net.navigateToURL;

public class AppTimer
{
// Create Time Object to fire every minute for 5 minutes
public var myTimer:Timer = new Timer(60000,5);

public function AppTimer()
{
// designates listeners for the completion event
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);

// starts the timer ticking
myTimer.start();
}

// Function restarts the timer.
public function resetTimer():void
{
myTimer.reset();
myTimer.start();
}

// Function gets called when timer runs out. Reloads the page
public function onTimerComplete(evt:Event):void
{
var ref:URLRequest = new URLRequest("javascript:location.reload(true)");
navigateToURL(ref, "_self");
}

}
}
Main.MXML File
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns="*" creationComplete="initApp()">
<mx:Script>
<![CDATA[

// Creates the AppTimer Object
public var myTimer:AppTimer = new AppTimer();

// Function to run when app is created
private function initApp():void
{
// Add Event listner to track mouse clicks
application.addEventListener(MouseEvent.CLICK, globalClickEvent);
}

// Everytime a user clicks in the applicatoin run this function.
private function globalClickEvent(event:MouseEvent):void
{
myTimer.resetTimer(); // Call timer reset function
}

]]>
</mx:Script>
<mx:Panel width="100%" height="100%" title="My App with Timer"/>
</mx:Application>

If anyone knows a better way to accomplish the same task I would be interested to hear about it.