Buttons and Events

If you’re like me you probably never used Event Listeners in AS2. Not unless you needed to do something “crazy” (insert sarcasm here at how amateur I was then, I’m only slightly less amateur now but that’s besides the point)

Well AS3 is all about Event Listeners, well Events actually. Actionscript is an Event based language. When something happens it dispatches an Event of some form and you have to react to it to make things go.

Wiring up buttons is a great way to introduce the concept of listening for and responding to events and has the upside of being THE MOST BASIC THING YOU EVER HAVE TO DO when building a website or anything that requires users to interact with an interface. So lets get started because we have clients waiting.

If you don’t want to read and just want the code – Click Here

Button Clicks

In AS 2 you wrote something like this:

myButton.onRelease = function(){

doSomething();

}

Here is the AS3 equivalent:

myButton.addEventListener(MouseEvent.CLICK,click_handler_function);

function click_handler_function(e:MouseEvent):void{

doSomething();

}

What the hell?! That’s way more code! No worries, I’ll talk you through it. So lets look at registering the EventListener. That part is pretty simple. We are adding the EventListener to the myButton clip with myButton.addEventListener.

We then need to pass some parameters to addEventListener.

The first one, MouseEvent.CLICK, is the event that we’re listening for from the object that we’ve added the listener to. (There are many other Mouse events we can listen for and they can be found in either the help docs or in code hinting). The second parameter, click_handler_fuction, is the function that is called once the Event is heard. You must tell the function that it is to expect an argument that is of type MouseEvent – I used e for the name of the argument but you can use whatever you like if you want to be different.

click_handler_function(e:MouseEvent)

The next step is to actually write the function and then you’re done. Your new button will doSomething() when clicked.

Here is the final code that will send the message “The Button Was Clicked” to the out put window.

myButton.addEventListener(MouseEvent.CLICK,click_handler_function);

function click_handler_function(e:MouseEvent):void{

trace(“The Button Was Clicked”);

}

Leave a Reply

Your email address will not be published. Required fields are marked *