AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

Using Event Listeners and Delegates



This sample takes a look at using ActionScript 2 classes to handles different aspects of displaying and gathering/sending information from a Flash form. One of the classes (ContactForm) is associated with a movieclip in the library; the other (Emailer) is not. The sample also makes use of EventDispatcher (built into Flash) to listen for and react to asynchronous events, and the Delegate class (also built in, as of version 7.2) to set the scope for a callback function.

Side note: a simpler example

If you're looking for a simple email form that can be used with either Flash MX or Flash MX 2004 and PHP, and doesn't involve classes, eventDispatcher or Delegates, code for that may be found on the contact form page.

The AS2 Email Sample

The sample above is set up to allow a contact form to be opened and closed with the click of a button (because such a form is almost always used within the context of a bigger site or Flash movie). When the button (a v2 component, which is used in this case as a toggle button) displays the label 'Contact', clicking it causes a movieclip from the library (contactForm) to be attached to the stage. That movieclip is the contact form, and is associated by its linkage settings to a class, com.flashcreations.ContactForm, which is stored in file ContactForm.as in either directory com/flashcreations under the directory with the fla, or in a special class directory on your machine.

The contactForm movieclip has several components in it: a combobox for allowing selection of a predefined subject (or entry of a new one), a checkbox to see if the user wants a reply, and a Send button to initiate a simple field validation before sending the email or displaying an appropriate response. Some initial setup of the components is done manually in the IDE, including setting up the combobox:

Another class, Emailer (com.flashcreations.Emailer), is used to carry out the communications with the serverside script that sends the mail. When ContactForm is attached, its class constructor creates an instance of Emailer (emailer), which it uses for communications. It will cause the form contents to be emailed by calling emailer.sendEmail (which in turn calls a serverside PHP script) and will wait for and respond to a broadcast from emailer saying that mail has been sent (or not, if an error occurred). Because it must wait for a response from emailer, the ContactForm movieclip must be set to be a listener to emailer, and must specify which of its routines is to be called when emailer broadcasts a message that email has been sent.

In the same way, a listener needs to be set up for the ContactForm's Send button so that method checkFields will be called when the button is clicked. One way of setting this up is with this statement in the ContactForm constructor:

pbSend.addEventListener("click", checkFields);

which causes ContactForm's checkFields routine to be called when pbSend is clicked. The problem with that statement is that it will set the scope of checkFields (the place where variables and functions are looked for by default) to the button pbSend, not ContactForm itself. So if you want to call other ContactForm methods from within checkFields, you can't call them directly without creating a reference from pbSend back to its owner. The need for this sort of workaround is neatly avoided with the addition in the 7.2 release of Flash of the Delegate class, which allows a scope to be specified. (The Delegate class must be imported into any class or Flash movie which uses it). In our case, replacing the statement above with this one will do that:

pbSend.addEventListener("click", Delegate.create(this, checkFields));

Now when checkFields is called, its scope is whatever was specified by the first parameter of the Delegate create call -- in this case, "this" which is ContactForm. That allows us to make direct calls to ContactForm methods validateFields, sendContent and showErrors from within checkFields.

The same method is also used for each of the following listener set ups:

Creating a form and its class

Within example_contact_as2.fla, the email form was created by dragging components out of the component window onto the stage and setting size and any other desired predefined parameters with the parameters panel. When complete, all items in the form were selected and converted to a movieclip called contact. The linkage for this movieclip was set to Export for Actionscript (in frame 1) with Identifier contact and linked to AS 2.0 class ContactForm (as you can see by right-clicking on contact in the library and choosing Linkage).

ContactForm.as was then created as a separate actionscript file (saved in the same directory as the fla, or within a specific domain directory if you prefer). Emailer.as was also created as a separate actionscript file. An instance of ContactForm (a movieclip) is created when the contact movieclip is attached in frame 1 of the main movie. An instance of Emailer (an abstract class with no physical representation) is created within the constructor of the ContactForm movieclip with the statement

emailer = new Emailer();

It only exists when the ContactForm movieclip exists, as its only function is to provide communications services to ContactForm. In our example, Emailer calls a very simple PHP script (sendemail.php, in directory scripts) which both sends the email and returns a result code. It could call any other serverside script instead, or use Flash remoting (in which case Service, PendingCall and RelayResponder objects would be used instead of LoadVars but the structure could otherwise remain the same).

EventDispatcher

Emailer makes use of a very handy built-in function of Flash 7: EventDispatcher. This is the class which handles component events like clicks, selections from comboboxes, etc. In order to use it with a custom class, like Emailer, one must do four things in that class:

  1. Import the EventDispatcher class
  2. Declare addEventListener, removeEventListener and dispatchEvent functions as properties of the class
  3. Call EventDispatcher.Initialize with the instance of the custom class (from its constructor or an init routine)
  4. Use dispatchEvent to broadcast any custom event with parameters specified by the dispatched event object

The latter is used by Emailer to broadcast the mailSent event (which ContactForm is listening for). It is done with this line of code if the send is carried out:

dispatchEvent({target:this, type:'mailSent', errorFlag:Number(lv["faultCode"])});

where target specifies the broadcasting object (Emailer), type specifies the event name, and any other properties can be tacked on to specify other necessary information. In our case, errorFlag is an indicator of success/failure, as passed back from the LoadVars object. This object, sent as a parameter of dispatchEvent, can be used by the listener's routine to pull out information about the event, as is done in this line from ContactForm's onMailSent routine:

taResponse.text = errors[o.errorFlag];

o is the object passed from emailer, and errorFlag is the property set from the results of the LoadVars operation (errors is a private array of ContactForm containing error messages to be displayed).

Other things included in this example are some different varieties of v2 components (combobox, textArea, checkbox, toggle and plain button) to provide examples of their use, a check to see if email has already been sent from the same email address while the contact form is open, and setting a global font style for components in the application.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads