Event Handling
In this section, we will illustrate event handling mechanism in Flex. Events are the corner-stones for any UI oriented applications and it is the mechanism of establishing communication between the user and an application. Events are signaled as a result of some trigger performed by the user such as the click on a button or a hyperlink, entering data in a text field etc. Having said that, there can be cases where events are auto-generated too. For example, it is quite common to fire a validation event when data is being entered in text fields. In Flex, it is the responsibility of components to register themselves to events; the target action to be taken after an event has happened is done through event handlers.
Consider the following login form that illustrates the various types of events and its usage.
Download Adobe Flex Example Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" width="544" height="200"
applicationComplete="onCreationComplete(event)">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
function loginHandler(event:Event){
Alert.show("Button clicked");
}
function onKeyUp(event:Event){
Alert.show("KeyUp event emitted from " + event.target.toString());
}
function onCreationComplete(event:Event){
Alert.show("Application initialization is completed");
}
]]>
</fx:Script>
<s:Label x="143" y="34" text="Enter your username and password"
width="241" height="25" id="usernamePasswordLabel"
verticalAlign="middle" textAlign="center"
fontFamily="Times New Roman" fontSize="15" fontWeight="bold"/>
<mx:Form x="144" y="62">
<mx:FormItem id="usernameLabel" label="Username:" required="true" x="68" y="32">
<s:TextInput id="userName" x="167" y="33" keyUp="onKeyUp(event)">
</s:TextInput>
</mx:FormItem>
<mx:FormItem id="passwordLabel" label="Password:" required="true" x="68" y="63">
<s:TextInput id="password" displayAsPassword="true" x="167" y="62" keyUp="onKeyUp(event)">
</s:TextInput>
</mx:FormItem>
<mx:FormItem>
<s:Button id = "loginButton" label="Login" x="120" y="108" click="loginHandler(event)">
</s:Button>
</mx:FormItem>
</mx:Form>
</s:Application> |
The above application displays a login form that provides username and password capabilities along with a login button. To indicate that the components username/password belong to a form, the element ‘Form’ is used. The visual controls username, password and button are encapsulated as a combination of ‘FormItem’ and element that is specific to a control. Note that the above declaration dictates the usage of nested controls where for a form, we have a form item, and under a form item there can be text field or a button. Username and passwords must be mandatory, to denote this we have used the attribute ‘required’ for these controls which draws an asterisk (*) after the label names. This doesn’t mean that if someone didn’t enter any value for username/password, the validation will happen, this just provides an indication to the user of the application that the fields are mandatory. For a password field, the value entered by the user shouldn’t be displayed; instead the value should be masked with some pattern. To enable this support, the attribute ‘displayAsPassword’ is used which by default will mask the value entered by the user with ‘*’. Launching the application will bring up the browser similar to the following,
We have written event handlers for three different types of events – after the application initialization is complete, while entering data in the username and the text field components and when the user clicks the login button. Note that event handlers or any other Action script related programming has to be done within the ‘<fx:Script>’ block. Note that every event handler is written as a function that should take any implicit parameter of type ‘Event’. Also note how the formal parameter is used in the function declaration – the formal parameter name followed by its type, e.g event:Event. Within the implementation of the function, we have just alerted indicating that that particular event has happened through ‘Alert.show’.
Now that we have actually how event handlers can be written, it’s time to see how components are wired with events. The first event that occurs when the application initialization is complete is registered as part of the ‘Application’ declaration like the following,
1 | <s:Application applicationComplete="onCreationComplete(event)"> |
Note that the event name ‘applicationComplete’ is registered for the event handler ‘onCreationComplete’. Similarly, handling key events for text-based components is done through ‘keyUp’ events and for handling click buttons (applicable for a Button components), the event name ‘click’ is used.
Validating data
It is quite normal to validate the data entered by the user in any form of application before submitting them. Adobe Flex provides rich validation support; the framework comes up with built-in support for many of the commonly used validators that can validate data available in the form of string, text, date etc. Given below is the list of commonly used validators available in Adobe Flex, note that the list is not exhaustive.
- String Validator
- Number Validator
- Date Validator
- Phone Number Validator
- Email Address Validator
- Currency Validator
- Credit Card Validator
- ZipCode Validator
The usage of validator will be illustrated in this section with an example. The example application prompts the user to input various user details like name, age, date of birth, sex, country, state, email id, phone number, credit card number etc.
Have a look at the following code for the above form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" pageTitle="Enter User details"
backgroundColor="#B1A9A9">
<fx:Declarations>
<mx:StringValidator id="nameValidator" source="{username}" property="text"
minLength="4" maxLength="20" requiredFieldError="Name is mandatory."
tooShortError="Name is too short. Enter value which is atleast 4 characters"
tooLongError="Name value is too long. Enter value which is not more than 20 characters"/>
<mx:NumberValidator id="ageValidator" source="{age}" property="text" minValue="1" maxValue="100"
requiredFieldError="Age is mandatory" allowNegative="false"/>
<mx:PhoneNumberValidator id="phoneNoValidator" source="{phoneNumber}" property="text"
invalidCharError="Phone number is invalid" minDigits="8" requiredFieldError="Phone number is mandatory"
wrongLengthError="Error in phone number length"/>
<mx:EmailValidator id="emailValidator" source="{mailId}" property="text"
invalidCharError="Email id contains invalid chars" missingAtSignError="@ sign is missing"
missingPeriodInDomainError="Period sign is missing" missingUsernameError="Username is missing in email id"
requiredFieldError="Email address is mandatory"/>
<mx:CreditCardValidator id="ccValidator" source="{creditCardNo}" property="text"
invalidCharError="CC contains invalid characters" requiredFieldError="CC is mandatory"/>
<mx:ZipCodeValidator id="zipCodeValidator" source="{zipCode}" property="text"
invalidCharError="Zip Code value is invalid" requiredFieldError="Zip Code is mandatory"/>
</fx:Declarations>
<s:Label x="267" y="10" text="Fill in the user details given below
" height="24" width="311"
id="userDetailsLabel" fontWeight="bold"
verticalAlign="middle" textAlign="center" fontSize="18"/>
<mx:Form height="383" x="267" y="57" backgroundColor="#E77070" width="311" id="userDetailsForm" label="User Details">
<mx:FormItem label="Name" required="true" x="68" y="32">
<s:TextInput id="username" x="167" y="33">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Age:" required="true" x="68" y="63">
<s:TextInput id="age" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Sex:" required="true">
<s:RadioButton label="Male" groupName="sex"/>
<s:RadioButton label="Female" groupName="sex" width="81"/>
</mx:FormItem>
<mx:FormItem label="Date of Birth" required="true">
<s:TextInput id="dateOfBirth" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Phone Number" required="true">
<s:TextInput id="phoneNumber" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Email Id" required="true">
<s:TextInput id="mailId" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Credit Card No" required="true">
<s:TextInput id="creditCardNo" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Salary Per annum" required="true">
<s:TextInput id="salaryPerAnnum" x="167" y="62">
</s:TextInput>
</mx:FormItem>
<mx:FormItem label="Country" required="true">
<s:ComboBox id="country" x="167" y="62">
<s:ArrayList>
<fx:String>India</fx:String>
<fx:String>Australia</fx:String>
<fx:String>Pakistan</fx:String>
</s:ArrayList>
</s:ComboBox>
</mx:FormItem>
<mx:FormItem label="State" required="true">
<s:ComboBox id="state" x="167" y="62">
<s:ArrayList>
<fx:String>Tamil Nadu</fx:String>
<fx:String>Karnataka</fx:String>
</s:ArrayList>
</s:ComboBox>
</mx:FormItem>
<mx:FormItem label="Zip Code" required="true">
<s:TextInput id="zipCode" x="167" y="62">
</s:TextInput>
</mx:FormItem>
</mx:Form>
<s:Button label="Submit Details" id="submitDetails" x="363" y="461"/>
</s:Application> |
The section ‘<fx:Declarations>’ is used for defining the validators. Note that all the pre-built validators arise from the namespace ‘library://ns.adobe.com/flex/mx’ and hence the namespace prefix ‘mx’ (as declared) has to be used.
The general format for defining any validator is given below.
1 | <mx:TypeOfValidator id="<IdForValidator>" source="{ComponentId}" property="PropertyOfAComponent"/> |
In the above declaration, the type of validator represents the validator’s class type – e.g. StringValidator, NumericValidator etc. The attribute ‘id’ represents the unique identifier for a validator which can be made meaningful w.r.t to the component owning the validator. For example, to validate a ‘name’ field, we can give the value ‘nameValidator’ for the id attribute. The attribute ‘source’ binds the validator instance to be the component that requires validator and the value must be the identifier given for the component. For example, if the name field component is given a component id of ‘nameComponent’, then this value has to be given. A component will have multiple properties and which of the component’s property has to be validator can be given in the ‘property’ attribute, that said, it is very common to specify the property ‘text’ for text-based controls.
Have a look at the following declaration
1 2 3 4 | <mx:StringValidator id="nameValidator" source="{username}" property="text"
minLength="4" maxLength="20" requiredFieldError="Name is mandatory."
tooShortError="Name is too short. Enter value which is atleast 4 characters"
tooLongError="Name value is too long. Enter value which is not more than 20 characters"/> |
In the above code snippet, we have defined the ‘StringValidator’ to validate on the ‘text’ property for the component ‘username’. The validation will be fired on this component when the component loses focus. Note that we have given the minimum and the maximum length for the field as 4 and 20 which means that if these constraints are violated, then the messages as configured in the properties ‘tooShortError’ and ‘tooLongError’ will be displayed. We have made the ‘username’ field as mandatory by defining the property ‘requiredFieldError’. Likewise, all validators have special properties specific to that validator.










November 11, 2010
Adobe Flex