Pass an Event from .AS file to Flash Movie

An important part of being able to quickly create small Flash applications, is to be able to combine the use of custom classes (.as files), and code that is embedded in the Flash timeline through the use of custom events. 

For example, if you have a class that listens for events, (such as a navigation class, flash remoting, or media server class), it will need to be able to let the movie (or other class) that is using it know that such an event has occurred, and give the movie access to any information regarding that event. For this example I will be using a class that listens to several buttons located in a movie clip on the main stage.

*** download source ***

 

ButtonClass

 

package{

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.display.MovieClip;

public class ButtonClass extends EventDispatcher{
private var container:MovieClip;
private var btn:String;
private var currentButton:int = -1; 

public function ButtonClass(btnContainer:MovieClip, btnName:String, labelArray:Array):void{
var n:int;
container = btnContainer;
btn = btnName;
for(n=0;n<labelArray.length;n++){
enableButton(n, labelArray[n]);
}

private function enableButton(n:int, label:String):void{
container[btn + n].addEventListener(MouseEvent.CLICK, hit);
container[btn + n].buttonMode = true;
container[btn + n].useHandCursor = true;
container[btn + n].labelText.text = buttonLabel;
container[btn + n].labelText.mouseEnabled = false; 
function hit(e:MouseEvent):void{
mouseHit(n);
}

private function mouseHit(n:int):void{
currentButton = n;
dispatchEvent(new Event(“ButtonHit”));
}

public function get _currentButton():int{
return currentButton;

private function set _currentButton(buttonNum:int):void{
currentButton = buttonNum;

}

Flash Movie

 

The flash movie has a clip called buttonContainer on the main stage. Within this clip are 8 sequentially named buttons (button0 – button7) that have a dynamic text field called labelText contained within them. When a button is pressed, an event called “ButtonHit” is sent out from the instance of the ButtonClass. A trace of the buttons information is run, using the get function in ButtonClass. 

import ButtonClass;
var buttonLabelArray:Array = new Array();
buttonLabelArray = [‘home’, ‘about’, ‘portfolio’, ‘work’, ‘company’, ‘staff’, ‘mission’, ‘contact’];

var myButtons:ButtonClass = new ButtonClass(buttonClip, “button”, buttonLabelArray);

myButtons.addEventListener(“ButtonHit”, buttonPressed);

function buttonPressed(e:Event):void{
var bNum:int = myButtons._currentButton;
trace(“Button # ” + bNum + ” / ” + buttonLabelArray[bNum] + ” pressed.”);
}

About Curious Minds
We are a web development firm in New York and Chicago, providing development resources and consulting for websites and mobile apps since 2004.