Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

Coming Together

So far, we've covered the three fundamental services of Peachmail: login and registration, Address Book, and Email Services. This section discusses some of the more advanced ActionScript concepts used by Peachmail, including custom classes and local connections. In addition, we recap the application's architecture, listing the custom classes that were created specifically for this application and their purpose.

Advanced ActionScript

One of the benefits of Flash MX is the use of components to ease development, with Peachmail making extensive use of Macromedia's listbox component. With this in mind, we'll explore the listbox methods used by Peachmail. We'll also look at how Peachmail uses Local Connection objects to send data between two swf files running externally. Finally, we cover prototyping and how Peachmail creates custom classes, leading right into the discussion of Peachmail's architecture and its custom classes.

Macromedia Components: Using the Listbox Component

Peachmail uses Macromedia's listbox component to display the addresses in the Address Book, the folders in the email folders listing, and the messages in the email messages listing. We'll discuss the most common list box methods used by Peachmail: addItem(), getSelectedItem(), and setChangeHandler(). addItem() is called when the user adds an address to the address book, or when the user logs in and the folder list is automatically updated, or when the user clicks on a folder and the messages list is updated. For example,

this.listbox.addItem(name, id); 

creates a record in the listbox containing the name and id and displays the name variable on the screen in the listbox—the name variable is the label part of the listbox and the id is the data part. These parts of the listbox can be referred to by the following code:

mylabel = this.listbox.getSelectedItem().label;
mydata = this.listbox.getSelectedItem().data; 

where getSelectedItem() is the currently selected item in the listbox. When Joe selects an item from the listbox, the listbox's onChange() event is automatically invoked. In the case of Peachmail's folder list for example, we showed that by calling the listbox's setChangeHandler() method to reassign its onChange() event, the onChange() event is set to retrieve the messages for the selected folder. The following example shows exactly that, where the "onChange" refers to the onChange() function in the folderList Class:

this.listbox.setChangeHandler("onChange", this);
folderList.prototype.onChange = function () {
   // call callback function, with the selected folder
   this.onSelect(this.listbox.getSelectedItem());
} 

One last thing to point out regarding Peachmail's use of the listbox is how the custom emailList Class uses the addItem() method:

this.listBox.addItem(email.sender, email.subject,
 email.ReceiveDate, {id: email.id, email: email.email,
 emailObject: email});

You'll notice how more than two parameters are being passed to addItem(). This is because the messages listbox is a modified version of the standard Macromedia listbox, and is extended to receive more than one parameter. We'll discuss extending classes a bit later, but for now, this is what the extended addItem() method looks like:

FEmailListBoxClass.prototype.addItem = function(name,
 subject, date, data)
{
   if (!this.enable) return;
   this.dataProvider.addItem({name:name, subject:subject,
    date:date, data:data});
} 

SWF to SWF: The Local Connection Class

LocalConnection objects are new in Flash MX and are used by Peachmail in circumstances such as sending data from the newAddress.swf in one window to the AddressBook.swf in another window. A local connection requires a sender .swf and a receiver .swf (Figure 7.16).

Figure 7.16Figure 7.16 Connecting two external .swf files.

The receiver .swf contains the following code:

RecvLC = new LocalConnection();
RecvLC.myfunc = function(msg) {
   trace("The sender has just sent me a message:");
   trace(msg);
}
RecvLC.connect("TheLC"); 

To communicate with the receiver, the sender .swf has the following code:

SendrLC = new LocalConnection();
SendrLC.send("TheLC", "myfunc", "Your fly is open."); 

When the example runs, the receiver readies itself for a connection from an external source to "TheLC". When the sender sends the message to "TheLC", it calls the receiver's "myfunc" function passing a string, which the receiver traces to the Flash MX Output window.

In Peachmail, the local connection for the Address Book screen looks like this:

newAddressConnection = new popupConnection ("newAddress",
 false);
newAddressConnection.newAddress = function (name, email) {
   // create the new address
   addAddress(name, email);
} 

Notice how newAddressConnection is a popupConnection object rather than the LocalConnection object. popupConnection is a custom class that handles the creation of a LocalConnection object and calls the connect() method to set this swf up as a receiver. Let's take a look at popupConnection's constructor:

global.popupConnection = function(connectionName, popup) {
   // store the connection name
   this.connectionName = connectionName;
   // store whether this is a popup
   this.popup = popup;
   // start a queue
   this.queue = [];
   // start up the popup connection
   this.start();
};
// inherit from local connection
popupConnection.prototype = new LocalConnection(); 

When a popupConnection is constructed, it inherits from LocalConnection(), meaning it attains the same properties and methods of LocalConnection() with the potential to extend the class. Extending the class means to define a new method for this class while still having access to the methods of the parent class—you'll see an example of this later. The last line of the constructor for popupConnection() triggers the class' start() method:

popupConnection.prototype.start = function() {
   // check whether this is a popup
   if (this.popup) {
     // connect
     this.connect(this.connectionName+"Popup");
   } else {
     // connect this.connect(this.connectionName);
   }
   // call the onConnect function in the other window
   this.send("onConnect");
}; 

Because this.popup is false in this scenario—defined false when newAddressConnection was created previously—the start() method goes on to run the connect() method of the popupConnection class, which by inheritance is the connect() method of the LocalConnection class:

this.connect("newAddress"); 

So now the Address Book is ready to receive data from any external .swf sending to newAddress.swf.

Before we get on to the sender code in the newAddress window, you may be curious about why the last line of the start() method calls the send() method of the popupConnection class. The send() method is actually extended from the parent class' send() method. This means all the functionality of the original LocalConnection class' send() is intact, but calling send() from a popupConnection object executes a different send() method. popupConnection.send() looks like this:

popupConnection.prototype.send = function() {
   // check whether this is a popup
   if (this.popup) {
     // add the connection name to the arguments
     arguments.unshift(this.connectionName);
   } else {
     // add the connection name to the arguemnts
     arguments.unshift(this.connectionName+"Popup");
   }
   // if this is connected or this is a popup
   if (this.connected or this.popup) {
     // call function in the other window
     super.send.apply(this, arguments);
   } else {
     // put in queue
     this.queue.push(arguments);
   }
}; 

To access the LocalConnection.send() from within popupConnection, the popupConnection class uses super.send() and the Function.apply() method:

super.send.apply(this, arguments); 

This results in calling the send method of the parent class with "arguments" as its list of arguments, and "this" is used to make the parent's send method relative to the popupConnection class.

When popupConnection.send() is called in the AddressBook.swf, it adds "newAddressPopup" to the beginning of its arguments in the line:

arguments.unshift(this.connectionName+"Popup"); 

and then adds the arguments to the queue:

this.queue.push(arguments); 

so that at this stage, newAddressConnection.queue would contain:

[ ["newAddressPopup", "onConnect"] ] 

Moving on to the Local Connection object for the sender, the NewAddress.swf contains the following code:

newAddressConnection = new popupConnection("newAddress",
 true); 

Tracing through the construction of newAddress.swf's newAddressConnection, we can see that one of the first actions is to set itself up as a data receiver in "newAddressPopup" with the line:

this.connect(this.connectionName+"Popup"); 

The next step calls the send() method:

this.send("onConnect"); 

which adds the string "newAddress" to the beginning of the arguments:

arguments.unshift(this.connectionName); 

and then calls the Local Connection send() method:

super.send.apply(this, arguments); 

so that the final call looks like this in the newAddress.swf:

newAddress.super.send("newAddress", "onConnect"); 

This sets up newAddress.swf to connect to a local connection named "newAddress" and execute newAddress' onConnect() method. Because we set up AddressBook to be the newAddress receiver, the onConnect() method of the AddressBook's local connection object is executed:

// called when connected with the popup
popupConnection.prototype.onConnect = function() {
   // change the connected flag
   this.connected = true;
   // loop through queue
   for (i = 0; i < this.queue.length; i++) {
     // send function
     super.send.apply(this, this.queue[i]);
   }
   // call the onFinishQueue handler
   this.onFinishQueue();
}; 

As you can see, the AddressBook's connected flag is set to true and it communicates back to newAddress.swf that it is connected by looping through its queue and applying the queue element to super.send() to get:

newAddressConnection.super.send("newAddressPopup",
 "onConnect"); 

On the newAddress.swf side, its onConnect() method is triggered and thus its connected flag is also set to true. As it doesn't contain any elements in its queue, the connection process ends there. So finally, after all this, we have two-way communication between AddressBook.swf and newAddress.swf.

Keeping in mind everything we've discussed so far is just to set up the communication between the two .swfs, the actual code to send the new address data from newAddress.swf to AddressBook.swf is executed when the Create button in newAddress.swf is clicked and its handler is triggered:

createHandler = function () {
   // change the address
   newAddressConnection.send("newAddress", name.text,
    email.text); // close this window
   getURL("javascript:void(window.close());");
} 

This finally calls the Address Book's newAddressConnection.newAddress() method, defined at the beginning of the Address Book discussion in this section, to process the name.text and email.text data from newAddress.swf.

Prototyping: Creating Custom Classes

By definition, a class is a group of properties, methods and events used to create objects in Flash. The MovieClip() class for example, contains properties such as _x, _width, _name, _visible, and so on; methods such as gotoAndStop(), attachMovie(), getDepth(), hitTest(), and so forth; and events like onEnterFrame and onLoad.

Peachmail contains several custom classes, such as ServerData(), buildBaseRequest(), folderList(), emailList(), and AddressBook(). We'll use ServerData() as an example to see how a custom class is created.

In Peachmail, server is made an object of the ServerData() class using the new operator:

global.server = new ServerData(); 

This gives server the properties, methods, and events of the ServerData() class. For example, the following are now valid:

server.setMethod(server.SEND_AND_LOAD);
server.setLanguage(server.JAVA); 

where setMethod and setLanguage are methods of the ServerData() class.

Creating a class first involves creating the constructor function. This function is called when an object is created from a class, such as when the new operator is used, as in the previous example. A constructor's purpose is to initialize the newly created object with any startup parameters. If no initialization is required, an empty function is still valid, such as:

function myClass() {
} 

Here is the constructor for the ServerData() class:

function ServerData() {
   // Create all language constants
   this.NOT_SPECIFIED = 0;
   this.COLD_FUSION = 1;
   this.ASP = 2;
   this.ASPNET = 3;
   this.PHP = 4;
   this.JAVA = 5;
   // Create all method constants
   this.SEND = 1;
   this.LOAD = 2;
   this.SEND_AND_LOAD = 3;
   // Default the language
   this.setLanguage(this.NOT_SPECIFIED);
   // Default the method
   this.setMethod(this.SEND_AND_LOAD);
   // Default ignore white to true
   this.setIgnoreWhite(true);
} 

An important distinction to point out is the reference of this—it is used to qualify the respective property and/or method, insuring that it belongs to the current class. After the creation of the constructor, the next step is creating the class methods.

Class methods are defined by using the prototype property. For example:

myClass.prototype.mymethod = function() {
   // mymethod's code goes here
} 

Here are some examples of ServerData's methods, namely setLanguage() and execute():

ServerData.prototype.setLanguage = function(language) {
   this.language = language;
}
ServerData.prototype.execute = function() {
   // Blank out the status
   this.setStatus("");
   // Chose which method to execute
   switch(this.getMethod()) {
     // handle send
     case this.SEND:
        // execute the send method
        results = this.executeSend();
        break;
     // handle load
     case this.LOAD:
        // execute the load method
        results = this.executeLoad();
        break;
     // handle send and load
     case this.SEND_AND_LOAD:
        // execute the send and load method
        results = this.executeSendAndLoad();
        break;
     // handle anything that doesn't match
     default:
        // No method specified, throw an error
        this.setStatus("Error: Invalid method defined!");
        return false
   } // end switch
   // if the results are positive, no errors were encountered
   if(results) {
     this.setStatus("Command executed properly");
   }
   // return whatever the specified method returned
   return results;
} 

Completing the discussion on classes is the concept of inheritance. Classes can be made a subclass of a parent class, thereby inheriting all the properties, methods, and events of the parent class. This is the case with the popupConnection class we showed earlier in the section on Local Connections. popupConnection() is made a subclass of the LocalConnection class using the new operator:

popupConnection.prototype = new LocalConnection(); 

Therefore, popupConnection() is a subclass of LocalConnection() and has access to all of LocalConnection's methods. Lastly, when popupConnection. send() was defined, it overrode LocalConnection.send() without eliminating the capability to access the parent class' send() method. This is part of the idea of extending a class: to create a subclass of a parent class and adding your own methods to the subclass.

Peachmail Architecture

This section revisits some of the concepts of the Peachmail architecture: specifically, the create-send-callback action, standardized transactions, and listbox handling. For each area, a custom class was defined to handle the details of the work involved. This discussion briefly comments on each concept and shows details of its respective class.

Create-Send-Callback (The ServerData Class)

The create-send-callback action was used extensively throughout the Peachmail application. ServerData() is created to assist in putting together an object to handle the complexity of creating an XML transaction request, sending it to the server, and processing a callback function based on the result of the processed request.

The constants for ServerData()'s language getter/setter are:

  • NOT_SPECIFIED (default)
  • COLD_FUSION
  • ASP
  • ASPNET
  • PHP
  • JAVA

The constants for ServerData()'s method getter/setter are:

  • SEND
  • LOAD
  • SEND_AND_LOAD (default)

Table 7.2 lists the methods for ServerData().

Table 7.2 ServerData() Methods

METHOD

DESCRIPTION

execute()

Performs the method specified by getMethod() onto the XML specified by getDocOut() and/or getDocIn().

executeSend()

Called by execute() to perform an XML Send with data from getDocOut(); the data is formatted to the getLanguage() specs before sending.

executeLoad()

Called by execute() to perform an XML Load with data from getDocIn().

executeSendAndLoad()

Called by execute() to perform an XML Send and Load with data from getDocOut() and getDocIn() respectively; the data is formatted to the getLanguage() specs before sending.

loaded(success)

Called internally when an XML Load operation has completed, its purpose is to ensure the code can extend and add more functionality later; this also executes ServerData's onLoad() method.

onLoad(success)

Stubbed method for onLoad. Override this method to capture the data when the data is done loading.

getMethod()

Default is SEND_AND_LOAD.

setMethod(method)

To be used with method constants.

getDocIn()

Getter function for Serverdata.docIn, which contains the xml object to populate with the servers response.

setDocIn(xmldoc)

Setter function for Serverdata.docIn.

getDocOut()

Getter function for Serverdata.docOut, which contains the XML document to send to the server.

setDocOut(xmldoc)

Setter function for Serverdata.docOut.

getURL()

Getter function for the URL property of the xml object.

setURL(url)

Setter function for the URL property of the xml object.

getLanguage()

Default is NOT_SPECIFIED.

setLanguage(language)

To be used with language constants.

getIgnoreWhite()

Default is True.

setIgnoreWhite(value)

Set the ignoreWhite property for the XML.

getStatus()

Getter function for ServerData.status; status is a verbose message indicating the state of an XML transaction.

setStatus(status)

Setter function for ServerData.status.

toString()

Returns the string "ServerData".


Standardized Transactions (The buildBaseRequest Class)

The XML transactions have a specific layout that is used throughout Peachmail. Standardizing the XML Transaction requests and responses provides great benefits to developers and programmer analysts, as a strict syntax makes it easy to grasp the data layout for faster development and future modifications and enhancements. Looking back at the XML requests discussed earlier in this chapter, we can see that all the XML requests have the following pattern:

<Request>
   <TransactionType>
     [some transaction type ]
   </TransactionType>
   <Data>
     < [data var 1] >
      [some data]
     </[data var 1]>
        .
        .
        .
     <[data var n] >
        [some data]
     </[data var n]>
   </Data>
</Request> 

The purpose of buildBaseRequest is to centralize where the request is generated so that any future changes can be made with ease. The majority of the XML request setup takes place in the constructor, so it has been listed here for your reference.

Here's the buildBaseRequest() constructor:

function buildBaseRequest(transactionType) {
   // Create the XML Object
   this.doc = new XML();
   // Create the request node
   var requestNode = this.doc.createElement("Request");
   // Create the transaction node
   var transactionNode = this.doc.createElement
    ("TransactionType");
   // Create the transaction value
   var transactionNodeValue = this.doc.createTextNode
    (transactionType);
   // Populate the value of the transaction node
   transactionNode.appendChild(transactionNodeValue);
   // Create the data node
   var dataNode = this.doc.createElement("Data");
   // Append the transaction node to the request node
   requestNode.appendChild(transactionNode);
   // Append the data node to the request node
   requestNode.appendChild(dataNode);
   // Append the request node to the parent doc
   this.doc.appendChild(requestNode);
   // Return the completed document return this.doc;
}
// end buildBaseRequest function 

Table 7.3 lists the methods of buildBaseRequest.

Table 7.3 buildBaseRequest Methods

METHOD

DESCRIPTION

addData (newData, value, attributes)

Adds data to the XML document.

getDoc()

Returns the XML document.


Listbox Handlers (the AddressBook, folderList, and emailList Classes)

Three classes—AddressBook(), folderList(), and emailList()—were created to handle each of the listboxes of the Peachmail application. We've covered the details on how they are used throughout the chapter. For your reference, the following are the constructor and a table listing the methods for each of these classes (see Tables 7.4–7.6).

The AddressBook() constructor:

_global.addressBook = function (listbox) {
   // store the listbox reference this.listbox = listbox;
   // create an array to hold addresses this.addresses = [];
   // create an object to hold ids, for easy access this.ids = {};
} 

Table 7.4 AddressBook() Methods

METHOD

DESCRIPTION

addAddress (name, email, id)

Adds an address to the AddressBook list.

deleteAddress (id)

Deletes an address from the list given its id.

deleteSelectedAddress()

Deletes the currently selected address from the list.

getSelectedAddress ()

Returns the currently selected address in the list.

getSelectedIndex ()

Returns the index of the currently selected address in the list.


The folderList() constructor:

global.folderList = function (listbox) {
   // store the listbox
   this.listbox = listbox;
   // set the change handler
   this.listbox.setChangeHandler("onChange", this);
   // store an array with the folders
   this.folders = [];
}

Table 7.5 folderList() Methods

METHOD

DESCRIPTION

addFolder (name, id)

Adds a folder to the Folders list.

deleteFolder(name)

Deletes the folder from the list given its name.

deleteSelectedFolder ()

Deletes the selected folder from the list.

onChange()

Calls the callback function.


The emailList() constructor:

emailList = function (listbox) {
   // store listbox reference this.listBox = listbox;
   // create a new array to hold the emails
   this.emails = [];
   // create an object for easy referencing with ids
   this.ids = {};
   // change the change handler
   this.listBox.setChangeHandler("onChange", this);
} 

Table 7.6 emailList() Methods

METHOD

DESCRIPTION

setFolder (folder)

Sets a folder to be the current folder.

addEmail(email, folder)

Adds a message to the Messages list.

addAttachment (emailId, name, id)

Adds an attachment to the Attachments combobox.

deleteSelectedEmail ()

Deletes the selected email from the list.

getEmail(id)

Returns the email given the id from the list.

setAttachments(emailed, attachments)

Links an email to a set of attachments.

onChange()

Calls the callback function.

getSelectedEmail()

Returns the selected email from the list.


  • + Share This
  • 🔖 Save To Your Account