Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Accessing XML Data from Your Application

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Client Technologies - Adobe Flex 2 and Rich Internet Applications

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Accessing XML Data from Your Application

Flex has the ability to access XML natively, using the E4X (ECMAScript for XML) standard.

Accessing XML Data from Your Application

 

Flex has the ability to access XML natively, using the E4X (ECMAScript for XML) standard. In this example, we use this capability to create an address book application. Figure 18.7 loads an XML file containing names and addresses into the application and displays its contents in a DataGrid (Fig. 18.8). The application also displays the selected contact’s location in an embedded Yahoo! Map (Fig. 18.9). Finally, the application allows you to edit any of the selected contact’s data (Fig. 18.10). You can test a live version of this application at test.deitel.com/examples/iw3htp4/flex/addressBook/. Note that because this application makes requests over HTTP, it must be run from a web server. To learn how to set up your own web server, see Chapter 21.

 

1     <?xml version = "1.0" encoding = "utf-8"?>

 

2     <!-- Fig. 18.7: addressBook.mxml -->

 

3     <!-- HTTPService, Validators, and new UI elements -->

 

4     <mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml"

 

5           layout = "vertical"

 

6           xmlns:yahoo = "com.yahoo.webapis.maps.*"

 

7           creationComplete = "getContacts.send(); initMap();">

8

9           <!-- import XML file -->

 

10          <mx:HTTPService

 

11                 id = "getContacts"

 

12                 url = "contacts.xml"

 

13                 showBusyCursor = "true"

 

14                 resultFormat = "object"

 

15                 result = "addressCollection = ArrayCollection(

 

16                       getContacts.lastResult.contacts.contact )"

 

17                 fault = "Alert.show( event.fault.message )" />

 

 

18

19          <!-- validators for "Edit Contact" fields -->

 

20          <mx:StringValidator id = "firstnameValidator" source = "{ firstName }"

 

21                 property = "text" required = "true" trigger = "{ save }"

 

22                 triggerEvent = "click" valid = "saveContact()" />

 

23          <mx:StringValidator id = "lastnameValidator" source = "{ lastName }"

 

24                 property = "text" required = "false" />

 

25          <mx:ZipCodeValidator id = "zipValidator" source = "{ zipCode }"

 

26                 property = "text" required = "false" />

 

27          <mx:EmailValidator id = "emailValidator" source = "{ eMail }"

 

28                 property = "text" required = "false" />

 

29          <mx:PhoneNumberValidator id = "phoneValidator" source = "{ phone }"

 

30                 property = "text" required = "false" />

31

32          <mx:Script>

 

33                 import mx.collections.ArrayCollection;

34

35                 // tell compiler to register an event for the addressCollection

 

36                 // variable, allowing it to be bound to another object

 

37                 [Bindable]

 

38                 private var addressCollection : ArrayCollection;

 

39          </mx:Script>

40

41          <!-- include ActionScript to implement search filter -->

 

42          <mx:Script source = "search.as" />

43

44          <!-- include ActionScript to implement Yahoo! Maps component -->

 

45          <mx:Script source = "map.as" />

46

47          <!-- include ActionScript to implement button actions -->

 

48          <mx:Script source = "buttonActions.as" />

49

50          <mx:Panel

 

51                 layout = "vertical" width = "100%" height = "100%"

 

52                 title = "Address Book">

 

53                 <mx:Accordion id = "accordion" width = "100%" height = "100%"

 

54                       creationPolicy = "all">

 

<mx:VBox label = "View Contacts">

56        <!-- search box, calls filter function on any change -->

57                    <mx:ApplicationControlBar>                                         

58                    <mx:Label text = "Search:" />

59                                <mx:TextInput id = "textFilter"              

60                                width = "100%"

61                                            change = "filter();"/>                     

62        </mx:ApplicationControlBar> <!-- End Search Box -->

63                                                                                           

64                    <!-- contacts data grid, populated with addressCollection -->      

65                    <!-- call setMarkerByAddress on change of selection -->   

66                    <mx:DataGrid id = "contactsView"       

67                    dataProvider = "{ addressCollection }"           

68                    width = "100%" height = "100%"           

69                    change = "setMarkerByAddress();">   

70                    <mx:columns>       

71                                                       

                        <mx:DataGridColumn dataField = "firstname"          

72                    headerText  = "First Name" />   

73                    <mx:DataGridColumn dataField = "lastname"          

74                    headerText  = "Last Name" />   

75                    <mx:DataGridColumn dataField = "street"     

76                    headerText  = "Street" />

77                    <mx:DataGridColumn dataField = "city"         

78                    headerText  = "City" />    

79                    <mx:DataGridColumn dataField = "state"      

80                    headerText  = "State" />  

81                    <mx:DataGridColumn dataField = "zip"          

82                    headerText  = "Zip" />      

83                    <mx:DataGridColumn dataField = "email"     

84                    headerText  = "E-Mail" />

85                    <mx:DataGridColumn dataField = "phone"   

86                    headerText  = "Phone Number" />       

87                    </mx:columns>                              

88        </mx:DataGrid>                                                      

89                                                                               

90        <mx:ControlBar>                                       

91                    <!-- start         contact action buttons -->           

92                    <mx:Button  label   = "New"                   

93                    click =            "newContact()" />             

94                    <mx:Button  label = "Delete"      

95                    click =            "Alert.show( 'Are you sure?',     

96                    'Delete           Contact',      

97                    mx.controls.Alert.YES | mx.controls.Alert.CANCEL,           

98                    this, deleteContact );" />  

99                    <mx:Button  label = "Get Directions"   

100                 click =            "getDirections();" />          

101                 <mx:Button  label = "Edit"          

102                 click =            "accordion.selectedIndex = 2;" />        

103                 <mx:Button  label = "View on Map"      

104                 click =            "accordion.selectedIndex = 1;" />        

105                 <mx:Button  label = "E-Mail"      

106                 click =            "emailContact();" />          

107                 <!-- end contact action buttons -->       

108                           </mx:ControlBar>

 

109                     </mx:VBox> <!-- end "View Contacts" Section -->

110        

111                     <mx:VBox label = "Map View">

 

112                           <!-- create Yahoo! Map -->

 

<yahoo:YahooMapService id = "yahooMap" UUID = "{ UUID }"

114     swfDomId = "{ swfDomID }"                   

115                 apiId =            "{ YahooAPIKey }"            

116                 mapURL = "{ mapURL }" width = "600" height = "400" />              

117     <mx:Button  label = "Back to Contacts"         

118                 click =            "accordion.selectedIndex = 0;" />        

119     </mx:VBox> <!-- end "Map View" Section -->

120                                                    

121                     <mx:VBox label = "Edit Contact">

 

<!-- begin edit contact form, set default button to "save" -->

 

123     <mx:Form width = "100%" backgroundColor = "#ffffff"                            

124                 defaultButton = "{ save }">                                 

125                 <!-- edit contact text fields, bound to data -->

126                             <mx:FormItem label = "First Name:" required = "true">                 

127                             <mx:TextInput id = "firstName"             

128                             text = "{ contactsView.selectedItem.firstname }" />             

129                 </mx:FormItem>     

130                 <mx:FormItem label = "Last Name:">  

131                             <mx:TextInput id = "lastName" 

132                             text = "{ contactsView.selectedItem.lastname }" />  

133                 </mx:FormItem>     

134                 <mx:FormItem label = "Street Address:">      

135                             <mx:TextInput id = "streetAddress"    

136                             text = "{ contactsView.selectedItem.street }" />        

137                 </mx:FormItem>     

138                 <mx:FormItem label = "City:">   

139                             <mx:TextInput id = "city"

140                             text = "{ contactsView.selectedItem.city }" />

141                 </mx:FormItem>     

142                 <mx:FormItem label = "State:">

143                             <mx:TextInput id = "state"          

144                             text = "{ contactsView.selectedItem.state }" />          

145                 </mx:FormItem>     

146                 <mx:FormItem label = "Zip Code:">     

147                             <mx:TextInput id = "zipCode"   

148                             text = "{ contactsView.selectedItem.zip }" /> 

149                 </mx:FormItem>     

150                 <mx:FormItem label = "E-Mail Address:">      

151                             <mx:TextInput id = "eMail"         

152                             text = "{ contactsView.selectedItem.email }" />         

153                 </mx:FormItem>     

154                 <mx:FormItem label = "Phone Number:">     

155                             <mx:TextInput id = "phone"       

156                             text = "{ contactsView.selectedItem.phone }" />       

157                 </mx:FormItem>     

158                 <!-- end contact text fields -->     

159                                                                

160                 <!-- edit contact action buttons -->        

161                 <mx:FormItem>      

162                             <mx:Button id = "save" label = "Save" />       

163                 </mx:FormItem>     

164                 <mx:FormItem>      

165                             <!-- cancel button reverts fields to previous values -->       

166                             <!-- return user to "View Contacts" section -->         

167                             <mx:Button id = "cancel" label = "Cancel"    

168                             click = "cancelContact()" />        

169                 </mx:FormItem>     

170                 <mx:FormItem>      

171                             <!-- pull up "Delete Contact" dialog box -->   

172                             <mx:Button label = "Delete"       

173                             click = "Alert.show( 'Are you sure?',    

174                             'Delete Contact',    

175     mx.controls.Alert.YES | mx.controls.Alert.CANCEL,

176     this, deleteContact );" />  

177     </mx:FormItem>     

178                           </mx:Form> <!-- end edit contact form -->

 

179                     </mx:VBox> <!-- end "Edit Contact" Section -->

 

180               </mx:Accordion> <!-- end Accordion navigation element -->

 

181        </mx:Panel> <!-- end UI layout -->

 

182  </mx:Application>

 


 

Fig. 18.7 | HTTPService, validators and new UI elements.

 


We begin by looking at the user interface code in the Panel element (lines 50–181, Fig. 18.7). An Accordion element (lines 53–180) allows the user to easily navigate between multiple VBoxes. As you click the title of one VBox, it slides on top of the previ-ously active VBox. This Accordion contains three VBoxes, View Contacts, Map View, and Edit Contact (lines 55–109, 111–119, and 121–179, respectively). The Accordion attribute creationPolicy with the value "all" (line 54) forces the Flash player to load all components, even those that are not initially visible to the user. This is necessary to allow the Yahoo! Map to load before we create the map navigation elements.

 

Inside the View Contacts VBox (as seen in Fig. 18.8), we first define an Application-ControlBar container for the search field (line 57–62). An ApplicationControlBar is a type of ControlBar that can be placed anywhere or docked at the top of an application.


 

This ApplicationControlBar contains a Label explaining to the user what the text field is for, followed by the TextInput element itself (lines 59–61). This element’s change attribute indicates that the filter function (located in the search.as file) should be called whenever a change is made to the field, such as adding or removing characters. We’ll discuss the filter function in detail when we review the ActionScript code.

 

Lines 66–88 create a DataGrid element with a dataProvider attribute that specifies what data will fill the rows and columns. The dataProvider addressCollection is placed in curly braces (line 67) to indicate that the dataProvider is being bound to the Data-Grid—any changes to the addressCollection will be displayed in the DataGrid. This DataGrid also has a change attribute. This is set to call the setMarkerByAddress function located in the map.as file whenever the user selects a different contact, so that the map will update to display that contact’s location. In the DataGrid, we define each column using DataGridColumn elements inside a parent columns element. Each DataGridColumn (e.g., lines 71–72) has a dataField attribute that tells the element which data it should display, and a headerText attribute that defines the text in the column header.


Following the DataGrid are a series of Buttons that perform actions. These Buttons reside in a ControlBar container (lines 90–108), and each has a click attribute that defines the ActionScript code that will be executed when the user clicks the Button. For the New (lines 92–93), Get Directions (lines 99–100), and E-Mail (lines 105–106) Buttons, the code executed by click calls a function specific to that Button, located in button-Actions.as. For the Delete Button (94–98), the code executed by click calls the Alert.show function to display a dialog box confirming the user’s action. This specific call to the Alert.show function sends five parameters—text, title, flags (specifies which buttons should appear), parent, and closeHandler. For the Edit (lines 101–102) and View on Map (lines 103–104) Buttons, the click attribute sets the selectedIndex of the Accordion to the index of the appropriate VBox.

The next VBox is Map View (lines 111–119 in Fig. 18.7, as seen in Fig. 18.9), which contains two items. The first is the YahooMapService element (lines 113–116). Note that the namespace of this element is yahoo—line 6 defines the yahoo namespace, which directs the compiler to the com/yahoo/webapis/maps directory located in the base direc-tory of your application. This directory contains the YahooMapService.as file, which defines the YahooMapService element. This element has seven attributes. After the id, the next four are constants that we set in the ActionScript file for the Yahoo! Map, map.as.

The last two define the width and height of the map element. We discuss using the Yahoo! Maps API when we describe the map.as file. Following the map is a Button (lines 117–118) that when clicked switches to the View Contacts VBox.

 

The final VBox is Edit Contact (lines 121–179 in Fig. 18.7, as seen in Fig. 18.10). This element contains a Form element (lines 123–178) that groups the TextInput elements and the Button elements into a single entity. This aligns the elements and also allows us to specify such things as defaultButton (line 124), which is set to the Save Button. Each TextInput resides in a FormItem element, which can specify whether or not the item must be filled in via the required attribute. If this attribute is set to true, Flex will display a red asterisk next to the item. In the addressBook program, only the firstName field is required. When a user leaves this field blank and clicks the Save Button, the action is ignored and the firstName field is highlighted. This is an improvement over HTML forms, with which the user is notified of invalid data only after the form is sent to the server (though client-side validation can be performed with JavaScript).

 

Lines 20–30 create validator elements that check the contents of the TextInput ele-ments to ensure that the user entered data correctly. Flex provides preconfigured validators for Strings, zip codes, e-mail addresses, phone numbers and more. There are several attributes for a validator element. The source attribute specifies which object to validate. The required attribute specifies whether the user is required to fill in data. The trigger attribute determines which button to listen to. The triggerEvent attribute specifies which event from the trigger initiates validation. The valid attribute specifies what ActionScript to execute if the triggerEvent is triggered and the data is valid.

 

Lines 10–17 create an HTTPService named getContacts. An HTTPService down-loads a URL using the HTTP protocol. The send method of an HTTPService executes a request to the service, and can include parameters if the service requires them. We specify the url attribute to be contacts.xml (Fig. 18.11). We set the showBusyCursor attribute to true (line 13) so that the application displays a busy cursor while a request is being pro-cessed. We set the resultFormat to object (line 14), so that the XML is parsed as a tree of ActionScript objects. Some other valid resultFormats are array (which parses the tree as an array object), text (which returns the raw XML) and e4x (which allows you to use E4X expressions, explained in Section 18.4). The expression in the result attribute is exe-cuted when the HTTP request is complete. It stores each contact node from the HTTPS-ervice’s lastResult property into an ArrayCollection called addressCollection. We create this ArrayCollection in lines 37–38. The [Bindable] metadata tag allows the variable that follows to be bound. It does this by registering an event to keep track of changes to the variable. The fault attribute (line 17) of an HTTPService specifies what to do in the event of a failed request. In this example, a failed request triggers an Alert dis-playing the error message. Finally, we call the send method at line 7, using the Applica-tion’s creationComplete attribute. This attribute registers an event handler that is triggered after the Flash Player creates all of the interface elements.

 

1    <?xml version = "1.0" encoding = "utf-8" ?>

 

2    <!-- Fig. 18.11: contacts.xml -->

 

3    <!-- XML file containing contacts -->


4    <contacts>

 

5             <contact id = "1">

 

6                   <firstname>Sue</firstname>

 

7                      <lastname>Black</lastname>

 

8                      <street>77 Massachusetts Avenue</street>

 

9                      <city>Cambridge</city>

 

10                    <state>MA</state>

 

11                    <zip>02139</zip>

 

12                    <email>sue.black@email.com</email>

 

13                    <phone>555-555-5555</phone>

 

14           </contact>

 

15           <contact id = "2">

 

16                    <firstname>James</firstname>

 

17                    <lastname>Blue</lastname>

 

18                    <street>219 4th Avenue</street>

 

19                    <city>Seattle</city>

 

20                    <state>WA</state>

 

21                    <zip>98109</zip>

 

22                    <email>james.blue@email.com</email>

 

23                    <phone>555-555-5555</phone>

 

24           </contact>

 

25           <contact id = "3">

 

26                    <firstname>Mike</firstname>

 

27                    <lastname>Brown</lastname>

 

28                    <street>1315 Cestnut Street</street>

 

29                    <city>St. Louis</city>

 

30                    <state>MO</state>

 

31                    <zip>63103</zip>

 

32                    <email>mike.brown@email.com</email>

 

33                    <phone>555-555-5555</phone>

 

34           </contact>

 

35           <contact id = "4">

 

36                    <firstname>Meg</firstname>

 

37                    <lastname>Gold</lastname>

 

38                    <street>700 14th Street</street>

 

39                    <city>Denver</city>

 

40                    <state>CO</state>

 

41                    <zip>80206</zip>

 

42                    <email>meg.gold@email.com</email>

 

43                    <phone>555-555-5555</phone>

 

44           </contact>

 

45           <contact id = "5">

 

46                    <firstname>John</firstname>

 

47                    <lastname>Gray</lastname>

 

48                    <street>525 Arch Street</street>

 

49                    <city>Philadelphia</city>

 

50                    <state>PA</state>

 

51                    <zip>19106</zip>

 

52                    <email>john.gray@email.com</email>

 

53                    <phone>555-555-5555</phone>

 

54           </contact>

 

55   </contacts>


 

Fig. 18.11 | XML file containing contacts.

 

You can embed ActionScript in MXML through use of the Script tag (lines 32–39). To better organize the code, we also place ActionScript in separate .as files. The address-Book.mxml file includes these files using a Script element with a source attribute (lines 42–48). There are three script files—search.as, map.as and buttonActions.as. We now explain each of these ActionScript files.

 

Search Function ActionScript

 

The search.as ActionScript file (Fig. 18.12) contains the function filter (lines 3–8), which is called any time a change is made in the textFilter TextInput—as specified by the change attribute in line 61 of Fig. 18.7. This function defines addressCollection’s filterFunction (line 6) to be testMatch (lines 10–31). An ArrayCollection’s filter-Function is passed each item of the collection and returns true if the item matches the search criteria, and false otherwise. Function testMatch tests whether the searchTerm matches the text in any of the data fields of each item.

 

1    // Fig. 18.12: search.as

 

2    // Using a filterFunction for a live search feature

 

3    private function filter() : void

4    {

 

5          // define filter function

 

6          addressCollection.filterFunction = testMatch;

 

7          addressCollection.refresh(); // refresh data to only display matches

 

8    } // end function filter

9

10   private function testMatch( item : Object ) : Boolean

11   {

 

12         // save search term to variable

 

13         var searchTerm:String = textFilter.text.toLowerCase();

14          

15         // return whether search parameter matches any field for each item

 

16         return( item.firstname.toLowerCase().search( searchTerm ) != -1 ||

 

17                item.lastname.toLowerCase().search( searchTerm ) != -1 ||

 

18                item.street.toLowerCase().search( searchTerm ) != -1 ||

 

19                item.city.toLowerCase().search( searchTerm ) != -1 ||

 

20                item.state.toLowerCase().search( searchTerm ) != -1 ||

 

21                String( item.zip ).search( searchTerm ) != -1 ||

 

22                item.email.toLowerCase().search( searchTerm ) != -1 ||

 

23                item.phone.toLowerCase().search( searchTerm ) != -1 )

 

24   } // end function testMatch

 

Fig. 18.12 | Using a filterFunction for a live search feature.

 

Yahoo! Map ActionScript

The map.as ActionScript file (Fig. 18.13) handles the addressBook application’s map functionality. We use the Yahoo! Maps API, because Yahoo! provides the ability to embed maps in Flex 2 applications3 (the map itself is a Flash application). The first step in using the Yahoo! Maps API is to get a Yahoo! account and Application ID. These are available at developer.yahoo.com. You then need to download the Yahoo! AS3 API Libraries at developer.yahoo.com/flash/as3_api_libraries.html. Move the source/as3/com/ folder and the source/as2/as2map.swf file into the base directory of your application. This allows you to use the as2map.swf file, which contains the ActionScript 2-based map, as well as use the ActionScript 3 functions Yahoo! provides to control the map.

 

1    // Fig. 18.13: map.as

 

2    // Handle the map functions for the Address Book application

 

3    import mx.managers.CursorManager;

 

4    import com.yahoo.webapis.maps.methodgroups.*;

 

5    import mx.controls.Alert;

6

7    // define constants

 

8    private const swfDomID : String = "addressBook";

 

9    private const UUID : int = Math.random() * 10000;

10          

11  // YahooAPIKey string must be your own from developer.yahoo.com

 

12  private const YahooAPIKey : String = "Your Yahoo API Key Here";

 

13  private const mapURL : String = "as2map.swf";

 

14  private var mapController : MapController;

15

16  private function initMap() : void

17  {

 

18         CursorManager.setBusyCursor(); // turn on busy cursor

19          

20         // wait for map to load, then call onMapLoaded method

 

21         yahooMap.addEventListener( 'onMapLoad', onMapLoaded );

 

22         yahooMap.addEventListener( 'onMapError', onMapError );

 

23  } // end function initMap

24

25  // handle map after it has loaded

 

26  public function onMapLoaded( event : Object ) : void

27  {

 

28         // instantiate map controller

 

29         mapController = new MapController( yahooMap );

30          

31         // instantiate panTool method

 

32         var panTools : PanTool = new PanTool( yahooMap );

33          

34         // allow user to pan across the map

 

35         panTools.setPanTool( true );

36

37         // instantiate the maps widget class

 

38         var widgets : Widgets = new Widgets( yahooMap );

39          

40         // activate Navigator widget

 

41         widgets.showNavigatorWidget();

42          

43         // activate map-type selection widget

 

44         widgets.showSatelliteControlWidget();

45          

46         // turn off busy cursor

 

47         CursorManager.removeBusyCursor();

 

} // end function onMapLoaded

50    public function onMapError( errorCode:String, httpStatus:String ) : void

51   {

 

52         Alert.show( errorCode + '\n' + httpStatus, 'Map Load Error' );

 

53   } // end function onMapError

54

55   // place a labeled marker at the currently selected address

 

56   public function setMarkerByAddress() : void

57   {

 

58         mapController.removeAllMarkers(); // clear previous markers

59          

60         // add marker at specified address,

 

61         // labeled with contact's name and address

 

62         mapController.addCustomPOIMarker(

 

63                ( contactsView.selectedItem.street + " " +

 

64                contactsView.selectedItem.city + " " +

 

65                contactsView.selectedItem.state ),

 

66                contactsView.selectedItem.firstname,

 

67                contactsView.selectedItem.lastname,

 

68                (contactsView.selectedItem.street + "\n" +

 

69                contactsView.selectedItem.city + ", " +

 

70                contactsView.selectedItem.state + " " +

 

71                contactsView.selectedItem.zip ),

 

72                0x990099, 0xFFFFFF );

73

74         // instantly center on address and zoom in

 

75         mapController.setCenterByAddressAndZoom(

 

76                contactsView.selectedItem.street + " " +

 

77                contactsView.selectedItem.city + " " +

 

78                contactsView.selectedItem.state, 5, 0 );

 

79   } // end function setMarkerByAddress

 

Fig. 18.13 | Handle the map functions for the Address Book application.

 

We first import the classes that we use in this ActionScript file (lines 3–5). The Cur-sorManager class allows us to set and remove the busy cursor. We also import all of the classes located in the com/yahoo/webapis/maps/methodgroups directory, which provide us with the ability to control the map and to create the map’s user interface widgets. We set the constants necessary for using a Yahoo! Map in lines 8–13. swfDomID (line 8) is a string that must be equal to the object id used in the .html file containing the applica-tion. UUID (line 9) is the unique ID of the map element and is set to Math.random()*10000 so that it is a random integer from 0 up to 9999. YahooAPIKey (lines 12) should be set to the Yahoo Application ID you obtained from developer.yahoo.com. Constant mapURL (line 13) is the path to the as2map.swf file. Because we placed that file in the base directory of the application, we can simply specify the file’s name. Line 14 creates the mapCon-troller variable that we will instantiate at line 29.

 

The function initMap (lines 16–23) is called when the application has finished creating the user interface elements, as specified by addressBook’s creationComplete attribute (line 7 in Fig. 18.7). This function sets the busy cursor, then registers event handlers for the onMapLoad and onMapError events for the map. The onMapError event han dler (lines 50–53) triggers an Alert displaying the error. The onMapLoaded event handler (lines 26–48) adds MapController, PanTool and Widgets objects to the map.

 

MapController enables programmatic control of the map’s location and zoom and the placing of markers on the map at a specified address.4 PanTool (line 32) enables the user to click and drag the map, as well as double click a location to center on it. Widgets (line 38) add the ability to show a navigator widget (line 41), which provides zoom con-trols and an overview map, and a satellite control widget (line 44), which provides the user with a selection of the regular map view, the satellite view, or the hybrid view. After loading all of the map’s functions, initMap removes the busy cursor (line 47).

 

Function setMarkerByAddress (lines 56–79) provides the ability to place a marker at the location of the selected contact’s location. It uses the mapController’s addCustom-POIMarker function (lines 62–72) to place a marker at the contact’s address that contains the contact’s first and last name as well as the address. It also uses the mapController’s setCenterByAddressAndZoom function (lines 75–78) to center the map on that contact’s location and zoom down to the street level (zoom level 5). The final parameter of the set-CenterByAddressAndZoom function is the amount of time in milliseconds the map should take to pan to the new location. We set this to 0, because the map will not be visible when this function is called.

 

Button Event-Handling ActionScript

The buttonActions.as ActionScript file (Fig. 18.14) handles the functionality of most of the addressBook application’s Buttons. Each Button has a corresponding function. The first Button it handles is the Cancel Button (lines 167–168 of Fig. 18.7). The cancelCon-tact function (lines 6–19 of Fig. 18.14) reverts Edit Contact’s fields back to the previous value of the selected contact, then switches the Accordion to View Contacts. The delete-Contact function (lines 22–35) handles when the user clicks a Delete Button (lines 94–98 or 172–176 of Fig. 18.7), then clicks Yes in the confirmation dialog box. It switches the Accordion to View Contacts if the user was not already there, and removes the currently selected contact. The emailContact function (lines 38–46 of Fig. 18.14) creates a new URLRequest object that contains a mailto URL for the current contact’s e-mail address. The call to navigateToURL opens that URL in _self, which refers to the current browser window. Since the URL is a mailto URL, however, the browser tells the user’s default e-mail client to open and to compose a new message addressed to the specified e-mail ad-dress. The getDirections function (lines 49–60) uses the same method to open a URL; however, instead of forming a mailto URL, it forms a URL pointing to the Yahoo! Maps page, specifying that we want directions ending at the currently selected contact’s address. It opens this URL in _blank, which creates a new browser window with the specified

 

URL. The saveContact function (lines 63–82) sets the data in the addressCollection item corresponding to the currently selected contact to be equal to that of the text in Edit Contact’s TextInputs. It then refreshes addressCollection in case the contactsView DataGrid is being filtered (the refresh ensures that the filter results are current). The newContact function (lines 85–93) creates a new item in addressCollection whose firstname is set to "New" and whose lastname is set to "Contact". It then sets the selectedIndex of the contactsView DataGrid to be the new item, and switches to the Edit Contacts view.

 

 

1     // Fig. 18.14: buttonActions.as

 

2     // Implement the actions of each button

 

3     import mx.events.CloseEvent;

4

5     // "Cancel" button

 

6     private function cancelContact() : void {

 

7           // revert edit fields to original value

 

8           firstName.text = contactsView.selectedItem.firstname;

 

9             lastName.text = contactsView.selectedItem.lastname;

 

10          streetAddress.text = contactsView.selectedItem.street;

 

11          city.text = contactsView.selectedItem.city;

 

12          state.text = contactsView.selectedItem.state;

 

13          zipCode.text = contactsView.selectedItem.zip;

 

14          eMail.text = contactsView.selectedItem.email;

 

15          phone.text = contactsView.selectedItem.phone;

 

16          // return user to "View Contacts" section

 

17          accordion.selectedIndex = 0;

 

18    } // end function cancelContact

20

21    // "Delete" button

 

22    private function deleteContact( event : CloseEvent ) : void

23    {

 

24          // handle if user clicked "Yes" in "Delete Contact" dialog box

 

25          if ( event.detail == Alert.YES )

26          {

 

27                 // return user to "View Contacts" section if

 

28                 // the user was in "Edit Contacts" section

 

29                 if ( accordion.selectedIndex == 2 )

 

30                       accordion.selectedIndex = 0;

31

32                 // remove selected contact

 

33                 addressCollection.removeItemAt( contactsView.selectedIndex );

 

34          } // end if

 

35    } // end function deleteContact

36

37    // "E-Mail" button

 

38    public function emailContact() : void

39    {

 

40          // form "mailto" URL given the selected e-mail address

 

41          var mailURL : URLRequest = new URLRequest( 'mailto:' +

 

42                 contactsView.selectedItem.email );

43

44          // open the URL without opening new window

 

45          navigateToURL( mailURL, "_self" );

 

46    } // end function emailContact

47

48    // "Directions" button

 

49    public function getDirections() : void

50    {

 

51          // form directions URL given the selected address

 

52          var directionsURL : URLRequest = new URLRequest(

 

'http://maps.yahoo.com/broadband#mvt=m&q2=' +

54                 contactsView.selectedItem.street + ' ' +

 

55                 contactsView.selectedItem.city + ' ' +

 

56                 contactsView.selectedItem.state +  ' ' +

 

57                 contactsView.selectedItem.zip );

 

58          // open URL in a new window

 

59          navigateToURL( directionsURL, "_blank" );

 

60    } // end function getDirections

61

62    // "Save" button

 

63    private function saveContact() : void

64    {

 

65          // write changes to data array

 

66          addressCollection.setItemAt( {

 

67                 firstname : firstName.text,

 

68                 lastname : lastName.text,

 

69                 street : streetAddress.text,

 

70                 city : city.text,

 

71                 state : state.text,

 

72                 zip : zipCode.text,

 

73                 email : eMail.text,

 

74                 phone : phone.text },

 

75                 contactsView.selectedIndex );

76           

77          // refresh data collection so that search will still work

 

78          addressCollection.refresh();

79

80          // return user to "View Contacts" section

 

81          accordion.selectedIndex = 0;

 

82    } // end function saveContact

83

84    // "New" button

 

85    private function newContact() : void

86    {

 

87          addressCollection.addItem( {

 

88                 firstname : 'New', lastname : 'Contact',

 

89                 street : null, city : null, state : null,

 

90                 zip : null, email : null, phone : null } );

 

91          contactsView.selectedIndex = addressCollection.length;

 

92          accordion.selectedIndex = 2;

 

93    } // end function newContact

 

Fig. 18.14 | Implement the actions of each button.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.