Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

O’Reilly Programming Flex 2 phần 7 docx
Nội dung xem thử
Mô tả chi tiết
266 | Chapter 12: Working with Data
Example 12-1. User class
package com.oreilly.programmingflex.data {
public class User {
private var _nameFirst:String;
private var _nameLast:String;
private var _email:String;
private var _lastLogin:Date;
private var _userType:uint;
public function get nameFirst( ):String {
return _nameFirst;
}
public function set nameFirst(value:String):void {
_nameFirst = nameFirst;
}
public function get nameLast( ):String {
return _nameLast;
}
public function set nameLast(value:String):void {
_nameLast = nameLast;
}
public function get email( ):String {
return _email;
}
public function set email(value:String):void {
var expression:RegExp = /\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
if(expression.test(value)) {
_email = value;
}
else {
_email = "invalid email";
}
}
public function get lastLogin( ):Date {
return _lastLogin;
}
public function set lastLogin(value:Date):void {
_lastLogin = lastLogin;
}
public function get userType( ):uint {
return _userType;
}
Using Data Models | 267
You can then create an instance of the model class using MXML or ActionScript.
With MXML, you have to define the namespace, then use <namespace:Class> to create the instance:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:data="com.oreilly.
programmingflex.data.*" layout="absolute">
<data:User id="user" email="[email protected]" lastLogin="{new Date( )}"
nameFirst="Abigail" nameLast="Smith" userType="1" />
</mx:Application>
With ActionScript, you need to import the class, and then use the constructor as part
of a new statement:
import com.oreilly.programmingflex.data.User;
private var user:User;
private function initializeHandler(event:Event):void {
user = new User( );
user.email = "[email protected]";
// etc.
}
In the next section, we’ll look at data binding. If you want to enable the data binding feature for a custom ActionScript-based data model, you must use the [Bindable]
metatag when declaring the class:
[Bindable]
public class User {
If you create the instance using MXML, the instance is automatically enabled for
data binding, assuming the class uses the [Bindable] metatag. However, if you create the instance using ActionScript, you must also use the [Bindable] tag when
declaring the variable you use to store the reference:
[Bindable]
private var user:User;
We’ll talk more about data binding and the [Bindable] metatag in the next section.
public function set userType(value:uint):void {
if(userType <= 2) {
_userType = userType;
}
}
public function User( ) {}
}
}
Example 12-1. User class (continued)
268 | Chapter 12: Working with Data
Data Binding
Flex applications typically utilize lots of data retrieved from both RPCs (server-side
method calls) and user input collected in forms. One way you can work with data is
to use extensive ActionScript. ActionScript provides low-level access to all the data in
your Flex application. Yet the ActionScript code can be redundant, and it can be
time-consuming to write. Although extensive ActionScript may be necessary in some
cases, the Flex framework provides a feature called data binding that simplifies working with data in most cases.
Data binding lets you associate data from one object with another. There are lots of
ways to use data binding. The following examples list a few of the most common
uses for data binding:
• Link form input controls (text inputs, checkboxes, etc.) with data models.
• Link two or more controls (e.g., display a slider value in a text component).
In the following sections, we’ll look at the rules of data binding as well as examples
of different ways to use data binding.
Understanding Data Binding Syntax
There are three ways to apply data binding:
• Curly brace ({}) syntax
• <mx:Binding>
• BindingUtils
Each technique for applying data binding has advantages and disadvantages, which
we’ll discuss in the next few sections.
Curly braces
Using curly braces to apply data binding is the simplest and fastest technique.
Throughout the early part of this book, you’ve seen quite a few examples of curlybrace syntax. Placing curly braces around any expression causes it to be evaluated.
Consider the following example with a combo box and a text input control:
<mx:HBox>
<mx:ComboBox id="level">
<mx:Array>
<mx:Object label="A" data="1" />
<mx:Object label="B" data="2" />
<mx:Object label="C" data="3" />
<mx:Object label="D" data="4" />
</mx:Array>
</mx:ComboBox>
<mx:TextInput id="selectedLevel" text="level.value" />
</mx:HBox>
Data Binding | 269
In this example, the text attribute of the text input is set to level.value. In that format, the value is interpreted literally, so the string level.value displays in the text
input. Changing the text input tag to the following makes a big difference:
<mx:TextInput id="selectedLevel" text="{level.value}" />
With this change, the text input now selects the data corresponding to the selected
combo box item. As the user selects a different combo box item, the value in the text
input also updates. This is because the text level.value is now placed within curly
braces, so it is treated as an expression rather than as literal text.
More than just evaluating the expression, the curly braces attempt to make a data
binding association. If the association is successful, as the value of the target (in the
example, the target is level.value) changes, the listening property (the text property
of the text input in this example) also updates. The preceding example illustrates this
because as the combo box value changes, so does the value displayed in the text
input. For a more dramatic example, consider the following:
<mx:Panel id="panel" width="{panelWidth.value}" height="{panelHeight.value}">
<mx:NumericStepper id="panelWidth" value="200" minimum="200"
maximum="400" stepSize="10" height="22"/>
<mx:NumericStepper id="panelHeight" value="200" minimum="200"
maximum="400" stepSize="10" height="22"/>
</mx:Panel>
In this example, the panel contains two nested numeric steppers. The panel uses data
binding to link the width property to the value of the first numeric stepper and the
height property to the value of the second stepper. The result is that as the user
changes the values of the numeric steppers, the width and height of the panel change
accordingly.
There are many scenarios in which you can use curly brace syntax for data binding.
As you’ve seen in the preceding example, you can use the syntax to directly associate
a target property with a property of a form control such as a text input. You can also
link a value from a control to a data model, as the following example illustrates:
<mx:Model id="dataModel">
<userData>
<email>{email.text}</email>
<phone>{phone.text}</phone>
<city>{city.text}</city>
<state>{state.value}</state>
</userData>
</mx:Model>
<mx:VBox>
<mx:Label text="Email" />
<mx:TextInput id="email" />
<mx:Label text="Phone" />
<mx:TextInput id="phone" />
<mx:Label text="City" />
<mx:TextInput id="city" />
270 | Chapter 12: Working with Data
<mx:Label text="State" />
<mx:ComboBox id="state">
<mx:Array>
<mx:Object label="CA" />
<mx:Object label="MA" />
</mx:Array>
</mx:ComboBox>
</mx:VBox>
The preceding code uses data binding to link the values from form controls to a data
model. You can use data binding both to assign values to a data model, as in the preceding example, and to retrieve data from a data model and display it. And you can
even use data binding in both directions at the same time. The following code, used
in conjunction with the preceding example, formats and displays the text from the
data model in a text area, updating as the user changes the values in the controls
bound to the model:
<mx:TextArea width="200" height="200" text="{'Contact Information\nEmail: ' +
dataModel.email + '\nPhone: ' + dataModel.phone + '\nLocation: ' +
dataModel.city + ', ' + dataModel.state}" />
Perhaps an even more useful example is one in which you use data binding to link
data either directly from controls or from a data model to an RPC component such
as a RemoteObject component. Using data binding in this way allows you to make
RPCs without having to write much, if any, ActionScript. The following example
uses data binding to link the data from the data model in the preceding example to a
RemoteObject instance as the parameters for a method call:
<mx:RemoteObject id="example" destination="exampleService">
<mx:method name="saveContactInformation">
<mx:arguments>
<email>{dataModel.email}</email>
<phone>{dataModel.phone}</phone>
<city>{dataModel.city}</city>
<state>{dataModel.state}</state>
</mx:arguments>
</mx:method>
</mx:RemoteObject>
As the values in the data model update via data binding, so too will the values in the
RemoteObject method arguments update. This allows you to call the method by simply calling a send( ) method with no parameters, as in the following example:
<mx:Button label="Save" click="example.saveContactInformation.send( )" />
This is a very simple example of working with RemoteObject. The same principles are
true when working with HTTPService and WebService as well. All of these RPC techniques are discussed in more detail in Chapter 14.
Because curly brace syntax allows you to evaluate any ActionScript expression, you
can also use data binding with E4X expressions. That means you can use data binding not only to link XML data with control values, but also to link controls and RPC