intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Flash Builder 4 and Flex 4 Bible- P12

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:50

95
lượt xem
14
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Flash Builder 4 and Flex 4 Bible- P12: When Macromedia first released Flash MX in 2002, the product was branded as the new way to build Rich Internet Applications (known by the acronym RIA). The term was invented at Macromedia to describe a new class of applications that would offer the benefits of being connected to the Internet, including access to various types of Web-based services, but would solve many of the nagging issues that had been inherent in browser-based applications since the mid-1990s....

Chủ đề:
Lưu

Nội dung Text: Flash Builder 4 and Flex 4 Bible- P12

  1. Chapter 17: Working with Pop-up Windows Working with Custom Pop-up Windows You can create custom pop-up windows in a Flex application for many purposes: l Presenting detailed information to the user that’s too complex to easily fit into an Alert dialog box l Collecting configuration and preference information before executing an operation l Providing a pop-up window that can be reused as a custom component l Collecting data through a data entry form wrapped in a pop-up window Tip A custom pop-up window component must be extended from a class that implements the IFlexDisplay Object interface. This interface is implemented by the UIComponent class, which in turn is in the inheri- tance hierarchy of all MX containers and controls. This essentially means that any component can be used as a custom pop-up window. If you want to create a custom pop-up window based on a Spark component, though, you should base your custom pop-up window on the Spark TitleWindow component. n Defining a custom pop-up window Custom pop-up windows can be defined as custom MXML components. If you want to create a window that looks like a dialog box, you can use either the Panel or TitleWindow container. While either component has the appearance of a dialog box, the Spark Panel component can’t be dragged around the screen by the user. If you want full dialog box functionality, create your cus- tom pop-up window components as subclasses of the TitleWindow component. Creating the component The steps for creating an MXML component that will be used as a pop-up window are the same as for any other MXML component: 1. Create a new MXML component based on spark.components.TitleWindow. 2. Save the new component in your project as a file with the .mxml file extension. The following code defines an MXML component designed to collect login information, and it might be saved as a file named LoginWindow.mxml: 521
  2. Part II: Designing Flex Applications Sharing data with events The custom component that will be used as a pop-up window should share information with the rest of the application using custom events. The LoginWindow component described in the pre- ceding code sample would share events for logging in and for canceling the operation. In order to share the login information, you need to create a custom event class to contain the login data. Listing 17.5 is a custom event class with public properties for the user name and password values that will be collected by the custom component. LISTING 17.5 A custom event class designed for use with a custom Login component package events { import flash.events.Event; public class LoginEvent extends Event { public var username:String; public var password:String; public function LoginEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } override public function clone():Event { var ev:LoginEvent = new LoginEvent(this.type); ev.username = this.username; ev.password = this.password; return ev; } } } On the Web The code in Listing 17.5 is available in the Web site files as LoginEvent.as in the chapter17 project’s src/events folder. n 522
  3. Chapter 17: Working with Pop-up Windows When the user clicks the custom component’s Log In button, the component shares data with the application by constructing and dispatching a custom event object: var event:LoginEvent = new LoginEvent(“login”); event.username = userInput.text; event.password = passwordInput.text; dispatchEvent(event); And if the user clicks Cancel, the custom component dispatches a cancel event, with the event object typed as the standard Event class: dispatchEvent(new Event(“cancel”)); Listing 17.6 shows a completed custom component designed for use as a pop-up window that can share data with the application using custom events. Nothing in the preceding code indicates that this component will be used as a pop-up window; it could just as easily be declared with an MXML tag set in the application to appear inline in the application. LISTING 17.6 A custom component ready for use as a pop-up window [Event(name=”login”, type=”events.LoginEvent”)] continued 523
  4. Part II: Designing Flex Applications LISTING 17.6 (continued) On the Web The code in Listing 17.6 is available in the Web site files as LoginTitleWindow.mxml in the chapter17 project’s src/popups folder. n Managing custom pop-up windows with the PopUpManager class The PopUpManager is a singleton class with static methods that you use to manage custom pop- up windows at runtime. It has two methods that you can use to present a pop-up window: l addPopUp(). Adds a new top-level window using a component that’s already been instantiated and is ready to use. l createPopUp(). Creates a new instance of a component, presents the component as a pop-up window, and returns a reference. Of these two methods, the addPopUp() method is more useful, because it enables you to con- struct and preconfigure a visual object prior to presenting it as a pop-up window. The PopUpManager also has these methods that you use to manipulate the position and order of pop-up windows: l bringToFront(). Gives top-level presentation and focus to a particular window. l centerPopUp(). Positions a pop-up window in the horizontal and vertical center of its parent window. Finally, PopUpManager has a removePopUp() method to remove top-level windows from the display when they’re no longer needed, though they will still exist in application memory. Adding a pop-up window to the display To add a new pop-up window to the application at runtime using the addPopUp() method, first declare an instance of the custom component you want to present. This declaration will likely be outside of any functions so the pop-up window reference persists between function calls: 524
  5. Chapter 17: Working with Pop-up Windows private var popup:LoginWindow; Within a function that you call to display the pop-up window, instantiate the component and cre- ate any required event listeners with accompanying event handler functions. The LoginWindow component in this example dispatches events named login and cancel, so it requires two addEventListener() calls: popup = new LoginWindow(); popup.addEventListener(“login”, loginHandler); popup.addEventListener(“cancel”, cancelHandler); To present the window on-screen, call PopUpManager.addPopUp() with these arguments: l childList:String. The display child list in which you’re adding the pop-up window. Possible values include PopUpManagerChildList.APPLICATION, PopUpManagerChildList.POPUP, and PopUpManagerChildList.PARENT (the default). l modal:Boolean. This argument determines whether the custom pop-up window is modal. If not passed in, it defaults to false. l parent:DisplayObject. The parent window over which the pop-up window is displayed. l window:IFlexDisplayObject. The component reference you just instantiated. After adding the pop-up window to the application interface, you can center the window over its parent window with a call to PopUpManager.centerPopUp(). If necessary, you can ensure that the new window has top-level focus with a call to PopUpManager.bringToFront(). This makes a call to PopUpManager.addPopup() to present the LoginWindow custom com- ponent as a modal pop-up window and then centers it on the parent component: PopUpManager.addPopUp(popup, this, true); PopUpManager.centerPopUp(popup); Caution If you don’t explicitly center the pop-up window with PopUpManager.centerPopUp(), the window appears in the top-left corner of the parent window. n Figure 17.11 shows the resulting pop-up window. Notice the application’s blurry appearance in the background, indicating that the user must dismiss the window before interacting with the rest of the application. Removing a pop-up window To remove a pop-up window, use the PopUpManager class’s static removePopUp() method. The method takes a single argument that references the pop-up window instance: PopUpManager.removePopUp(popup); 525
  6. Part II: Designing Flex Applications FIGURE 17.11 The LoginWindow component as a pop-up window can now be dragged by the user, and the rest of the application is disabled due to the modality of the pop-up. You also can call the method from within the component to cause it to remove itself from the interface: PopUpManager.removePopUp(this); The application in Listing 17.7 uses the LoginWindow component as a pop-up window. In each of its custom event handler functions, it explicitly closes the pop-up window with a call to PopUpManager.removePopUp(). LISTING 17.7 An application using a custom pop-up window
  7. Chapter 17: Working with Pop-up Windows popup.addEventListener(“cancel”, closeHandler); PopUpManager.addPopUp(popup, this, true) PopUpManager.centerPopUp(popup); popup.setInitialFocus(); } private function loginHandler(event:LoginEvent):void { Alert.show(“You logged in as “ + event.username + “ with a password of “ + event.password, “Login Successful”); PopUpManager.removePopUp(popup); } private function closeHandler(event:Event):void { Alert.show(“You cancelled the login operation”, “Login Cancelled”); PopUpManager.removePopUp(popup); } ]]> On the Web The code in Listing 17.7 is available in the Web site files as UseCustomPopUp.mxml in the chapter17 project. n The TitleWindow container is a subclass of Panel, so it shares all of that container’s features: It contains a title bar, a caption, a border, and a content area, and like the Panel, it can host a controlBarContent area with wizard-like buttons at the bottom. The TitleWindow displays a close button in its upper-right corner, creating a common visual interface for pop-up windows. The close button doesn’t actually close the pop-up window. Instead, it dispatches a close event with an event object typed as mx.events.CloseEvent. Upon instantiating the custom compo- nent (and prior to adding it as a pop-up window), create a listener for the close event: popup.addEventListener(CloseEvent.CLOSE, closeHandler); Then, in the event handler function, call PopUpManager.removePopUp() to remove the pop- up window from the application interface: private function closeHandler(event:CloseEvent):void { Alert.show(“You canceled the login operation”, “Login Canceled”); PopUpManager.removePopUp(popup); } 527
  8. Part II: Designing Flex Applications If you don’t want to display the close button in the custom pop-up window, just create a custom skin for your pop-up and modify it as needed. To do this, follow these steps: 1. Open the custom pop-up window file in Flash Builder’s Design mode. 2. Right-click anywhere on the design area and select Create Skin. 3. As shown in Figure 17.12, enter the package and name of the new skin you want to create. As with all custom components, you should place the skin component in a subfolder of the project’s source-code root. FIGURE 17.12 Creating a new custom skin based on the TitleWindow component’s default skin 4. Set Host component to spark.components.TitleWindow. 5. Select Create a copy of and use the default value spark.skins.spark. TitleWindowSkin (this is the default skin for the Spark TitleWindow component). 6. Click Finish to create the new custom skin. 7. When the new custom skin file appears in Flash Builder’s Design mode, click the close icon in the skin’s upper-right corner as shown in Figure 17.13. 8. Press Delete to remove the button from the skin. Alternatively, you can use Source mode and comment out the tag. 9. Save your changes. 528
  9. Chapter 17: Working with Pop-up Windows 10. Open the custom pop-up window file in Source mode and look at the starting tag. It now includes the skinClass attribute that assigns your new custom skin: FIGURE 17.13 The close button is a part of the Spark TitleWindow component’s skin and can be deleted. The TitleWindow skin’s default close button Note The TitleWindow component’s close icon is defined as an optional skin part, so when you delete it from the skin it doesn’t result in any compilation errors. n If you want to use the custom skin with all dialog boxes in your application, you can set the skinClass style in an embedded or external style sheet. For example, this CSS code assigns the new skin for all components that are based on the Spark TitleWindow component: @namespace s “library://ns.adobe.com/flex/spark”; s|TitleWindow { skinClass: ClassReference(“skins.CustomTitleWindowSkin”); } 529
  10. Part II: Designing Flex Applications Summary In this chapter, I described how to create pop-up windows as part of a Flex application interface. You learned the following: l Pop-up windows are typically used to present and collect information in a windowing style application. l You use the Alert class to present simple informational messages and to enable a user to confirm or decline an operation. l The PopUpMenuButton control combines a Button and single-level Menu that’s similar in presentation to a ComboBox. l You use the PopUpButton control to present any visual container or control as a pop-up window. l Custom pop-up windows are defined in the same way as any custom component. l The Spark TitleWindow is designed to be used as a custom pop-up window and enables dragging of the resulting window by the user. l You can remove the close button from the TitleWindow interface by creating a custom skin. l You use the PopUpManager class’s static methods to add and remove custom pop-up windows at runtime. 530
  11. Part III Working with Data IN THIS PART Chapter 18 Modeling and Managing Data Chapter 19 Using List Controls Chapter 20 Using Advanced List Controls Chapter 21 Using the Flex Charting Controls Chapter 22 Working with Data Entry Forms Chapter 23 Working with HTTPService and XML Chapter 24 Managing XML with E4X
  12. CHAPTER Modeling and Managing Data F lex applications are stateful; that is, they have the capability to remem- ber data persistently for the duration of the user’s session in a way IN THIS CHAPTER that classic Web applications usually don’t. One of the most common Using the tag tasks you must accomplish as an application developer is to create a frame- to model data items work for storing data that the application can use at runtime. Embedding data with The content of an application’s data can come from many sources: XML files, databases or other server-side resources, or remote functions wrapped by and exposed as SOAP-style or Representational State Transfer (REST)-style Creating value object classes Web services. Regardless of how the data comes to an application, though, a in ActionScript Flex application stores the data in exactly the same way: as a data model. Storing data sets in client memory with the In this chapter, I describe common techniques for modeling data in Flex ArrayList and applications. I start with creating single-object data models: ActionScript ArrayCollection classes classes designed to hold one instance of a data entity at a time. (A data instance might represent a row in a database table or a single element in an Filtering and sorting data with XML file.) You can represent such data instances with the tag, the ArrayCollection a generic data object, or, more commonly, you create your own custom class ActionScript classes, known variously by the design pattern names Value Traversing, searching, and Object and Transfer Object. bookmarking data objects In the second part of the chapter, I describe the use of data collections: with the IViewCursor interface ordered collections of data instances managed by the ArrayList and ArrayCollection classes. I describe how and where to declare these classes and then describe how to use the powerful ArrayCollection class to filter, sort, bookmark, and traverse data in client application memory. On the Web To use the sample code for this chapter, import the chapter18.fxp Flex project archive from the Web site files into your Flex Builder workspace. n 533
  13. Part III: Working with Data Creating a Data Model A data model is a way of representing data (information) in a client application. It’s a truism of database applications that you can’t do much without knowing your data structure. Take an appli- cation that represents the personal information of your contact list. Whether you store this data in an e-mail client or a complex server-side database application such as SQL Server or MySQL, the software that manages the data has to know its structure. In classic relational databases, data is stored in tables. Each table has columns that represent the bits of data that are created for each row in the table. A database table representing contact infor- mation might have any number of columns. Each column has a name and a data type. For exam- ple, a contacts table might have the data structure shown in Table 18.1. TABLE 18.1 A Simple Database Table Structure Column Name Primary Key Data Type Length Null OK contactId X Integer firstName String 50 lastName String 50 dob Date x address String 50 x city String 20 x zipCode String 10 x telephone String 15 x When data is returned to a Flex application in this structure, you need a way to store it. The goal is to create an object that can serve as a container for this data and can share this data structure to the best of the Flex framework’s capability. Figure 18.1 shows a UML diagram describing the structure of an object that would be able to hold this data. You can create a data model to store the data in two ways: by using the tag to declare a generic untyped data object and by creating a custom ActionScript class. Of these approaches, the custom ActionScript version is significantly more powerful and flexible. The approach is fast and easy to code, and it might be used during early prototyping of an application, but an application that’s built for durability and easy long-term maintenance gener- ally requires custom ActionScript classes to represent data in Flex application memory. 534
  14. Chapter 18: Modeling and Managing Data FIGURE 18.1 A UML diagram describing a class with data structure Contact − contactId : Integer + firstName : String + lastName : String + dob : Date + address : String + city : String + zipCode : String + telephone : String Using the element The element compiles XML markup into a generic ActionScript Object. New Feature The element was used with the mx prefix in previous versions of the Flex SDK. As with all nonvi- sual elements, it must be declared within an element in a Flex 4 application. n You could implement the data structure described in the UML diagram in Figure 18.1 as a data object with this code: 1 Joe Adams 123 Main Street Anywhere WA 12345 11/28/1959 555-123-4567 You also can fill Model properties dynamically from user interface components using binding expressions: 535
  15. Part III: Working with Data 0 {firstNameInput.text} {lastNameInput.text} {myDataField.selectedDate} ... additional elements and bindings... At runtime, as the user interacts with form controls, the controls’ values are passed to the Model object through the binding expressions. Caution The use of binding expressions to dynamically fill Model properties has an obvious benefit of creating and fill- ing a data object declaratively, but this technique also has a drawback that might not be immediately apparent. When you fill a Model property from a binding expression, its initial value is null. If you don’t explicitly set initial values with ActionScript statements, you can end up sending the data object to remote server functions such as Web services where null values can cause runtime errors. If you encounter this problem, an easy solution is to initialize the object’s properties upon application startup in an initialization function: myModel.firstName=””; myModel.lastName=””; On the other hand, setting default values is a built-in benefit of custom ActionScript classes used as value objects, described later in this chapter. n The application in Listing 18.1 declares a single data object using the tag and then displays its values in Label controls with binding expressions. LISTING 18.1 Declaring a data object with 1 Joe Adams 123 Main Street Anywhere WA 12345 11/28/1959 555-123-4567 536
  16. Chapter 18: Modeling and Managing Data On the Web The code in Listing 18.1 is available in the Web site files as ModelDemo.mxml in the chapter18 project. n Benefits of The advantage of the tag is its simplicity. It’s very easy to declare a bit of hard-coded data with these benefits: l The object and all its properties are automatically bindable. You don’t have to include the [Bindable] metadata tag, and you can refer to any of the object’s properties with binding expressions, as in: l The tag uses simple XML syntax to declare its property names. After a data object has been declared with the tag, you refer to its data using dot syntax. The object’s id, assigned in the start tag, actually refers to the model’s root element if there is a sole root element. In the preceding example, this element is named , but its name isn’t important; you refer to the root by the model object’s id and then to its named properties as child objects of the model: contact.firstName Drawbacks of These drawbacks of the tag prevent its being truly useful to model objects in pro- duction applications: l The properties are always String values; the architecture doesn’t give you any way to set specific data types. l You can declare only a single instance of an object. Unlike strongly typed ActionScript classes, which are designed to be instantiated as many times as necessary, if you want another data object you have to declare it explicitly. l Because is a compiler tag that doesn’t represent an ActionScript class, it has no methods or properties. 537
  17. Part III: Working with Data Importing data with The tag does have one very useful capability: It can be used to compile data into an application. This technique is useful only when two circumstances are true: l It is a relatively small amount of data. Large amounts of embedded data result in an increase in the size of the compiled application. For applications that are deployed over the Web, embedding data results in a slower download and longer delay before the appli- cation starts for the first time. On the positive side, the data is instantly available to the application without having to be downloaded at runtime. l The data is completely static. If any of the data under consideration might change dur- ing the lifetime of the application, you should load the data at runtime using the HTTPService component or another runtime loading mechanism. To embed data with the tag, first save it as an XML file. The names of the XML file’s data elements can be anything you like; the only requirements are that the XML file be well formed and have a single root element. The following XML structure is suitable for use with the tag: BU1032 How to Program Good 1528 409-56-7008 19.99 A guide to creating great software. 2005-01-15 ... additional elements ... Assuming the preceding XML markup is saved in a text file named books.xml in the project source root’s data subfolder, the code to import and embed the data looks like this: As with hard-coded data, the Model element’s id points to the XML structure’s root element. From there, the data typing of each element depends on the number of elements with a particular name. If the preceding structure contains two or more elements, the expression book- Data.book returns an Array. If the XML structure’s root element contains only a single child element, the expression bookData.book instead returns an ActionScript Object. 538
  18. Chapter 18: Modeling and Managing Data Tip To ensure that you always have an Array to work with, you can use the ArrayUtil.toArray() method wrapped around an expression that might return an Object due to the number of elements in the XML data structure. At application startup, declare a separate Array variable and fill it as shown here: import mx.utils.ArrayUtil; [Bindable] private var bookArray:Array; private function initApp():void { bookArray = ArrayUtil.toArray(bookData.book); } n Using Value Objects A value object, also known variously as a transfer object, a data transfer object, and a bean, is a class designed to hold data for a single instance of a data entity. The design pattern is named Transfer Object in the world of Java Enterprise Edition (JEE) application server development, where it’s implemented as a Java class. Web Resource The Transfer Object design pattern is described in the J2EE design pattern catalog at http://java.sun. com/blueprints/corej2eepatterns/Patterns/TransferObject.html. In the most recent ver- sion on the Sun Web site, the graphics still refer to the design pattern as Value Object, its old name. Don’t be confused; it’s really the same pattern! n Value object classes have these advantages over the tag: l Class properties can be strongly datatyped. Each property is declared with standard vari- able declaration syntax and typically has a data type declared after the colon: public var myDateProperty:Date; l Class properties can have default values. As when declaring a variable inside or outside a function, you can declare default values by appending the value after an = assignment operator. This code declares a Date property with the default set to the current date: public var myDateProperty:Date = new Date(); l You can use implicit setter and getter accessor methods. Accessor methods enable com- plex logic and authentication when setting or getting data and creating read-only proper- ties (properties that can be read from the application but can only be set internally within the value object class). l When you integrate a Flex client application with an application server that supports data transfer with AMF (Action Message Format), such as ColdFusion, BlazeDS, LiveCycle Data Services, PHP, and others, client-side value object classes defined in ActionScript can be mapped to equivalent classes on the server (written in the server’s native language, such as Java, ColdFusion Markup Language, PHP, or C#). This enables you to pass data between the application tiers with minimal code in both tiers. 539
  19. Part III: Working with Data Using the New ActionScript Class wizard You can use Flex Builder’s ActionScript Class wizard to create a simple ActionScript class. Follow these steps to create a new value object class to represent Book data: 1. Open the chapter18 project if it isn’t already open. Notice that the project contains a valueObjects package. 2. Right-click on the valueObjects package and select New ➪ ActionScript Class. 3. Set the class name as Contact, as shown in Figure 18.2. 4. Click Finish to create the new ActionScript class. FIGURE 18.2 The New ActionScript Class wizard The completed ActionScript class is created in the file Contact.as in the valueObjects folder and should appear in the Source view editor as follows: package valueObjects { public class Contact { 540
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2