- Flash MX Message Board Features
- Why Use Flash for a Message Board?
- How Our Message Board Works
- The User Interface: The Application
- ShowThreads, ShowMessages, Frames 20 and 30
- Summary
The User Interface: The Application
Copy MB.fla from the Chapter 3 folder on the CD-ROM and open it from your desktop to see the general look of the message board on the Stage. Note that the .fla is set up with labels across the top, which denote functions of the message board and are used in order to process the many message board functions.
Load, Frame 1
Right now we are concerned with the Actions layer (Figure 3.4). On the first frame on the Actions layer (labeled Load), you find the following ActionScript (which is part of the loading process):
// Include the server data object #include "ServerData.as" // Include the common transaction functions #include "CommonTransactionFunctions.as" // Include the loading panel code #include "LoadingPanel.as" // Include the error panel code #include "ErrorPanel.as" // Include the error panel code #include "MessagePanel.as" // Global variables global.loadingPanelDepth = 100; global.errorPanelDepth = 101; global.messagePanelDepth = 102; global.clipDepth = 1000; global.topicsLoaded = false; click = new Sound(); click.attachSound("click"); click.setVolume(50); // Configure the server data object sd = new ServerData(); sd.setMethod(sd.SEND_AND_LOAD); sd.setLanguage(sd.COLD_FUSION); sd.setURL("http://www.electrotank.com:8000/book/cf/mb/¨ Controller.cfm"); // Attach the loading panel root.attachMovie("LoadingPanel", "lPanel",¨ loadingPanelDepth); // Configure the panel lPanel.setTitle("Loading ServerSide MX Board"); lPanel.setMessage("0% loaded"); lPanel.centerClip(); // Get the size of the movie totalFileSize = _root.getBytesTotal(); // Start the event that checks to see if things are loaded root.onEnterFrame = function() { // See how much is loaded currently currentFileSize = _root.getBytesLoaded(); // Handle if its done or not if(currentFileSize < totalFileSize) { // Get percentage percent = (currentFileSize / totalFileSize) * 100; percent = Math.round(percent); // Update the message lPanel.setMessage(percent + "% loaded"); } else { // Kill the panel lPanel.unloadMovie(); // Kill this event _root.onEnterFrame = null; // Start executing again _root.nextFrame(); } } // end onLoad event // initiate click audio click = new Sound(); click.attachSound("click"); click.setVolume(50); // Stop the timeline from progressing stop();
Figure 3.4 The first frame in the Actions layer contains code for loading the SWF itself.
In this code you can see how the application takes shape. Several include files are declared that import the major application processing engine code upon SWF compiling and publishing. Feel free to go through this code on your own because there is simply too much of it to explain in the scope of this book. The code is heavily commented and that should go a long way in offering satisfactory explanations about it.
Global variables (new to Flash MX; variables that exist globally and can be called easily from anywhere) are defined, setting up the level position of interface elements, and the variable topicsLoaded is set to the Boolean of false (initially the topics are not loaded.) The server data model is defined next, including the server-side language and the location of the appropriate language HTTP page.
The loading panel (which gives graphical feedback on the SWF loading status) is configured for use. The lines below its configuration set and run the preloader information displayed in the loading panel (lPanel) and once the SWF has loaded, the panel is killed (no function association called upon onEnterFrame). If the SWF has preloaded, the movie progresses to the next frame, breaking it from the onEnterFrame loop of the preloader. The code also instantiates a sound object for rollover feedback that will be used in the topics display ScrollPane, which we'll look at shortly.
Load, Frame 2
On frame 2 of the Actions layer in the .FLA, you'll find the rest of the ActionScript that deals with loading the message board data itself:
// Include the properties manager class #include "PropertiesManager.as" pm = new PropertiesManager(); pm.load("MBProperties.xml"); pm.onLoad = propertiesLoaded; // Attach the loading panel root.attachMovie("LoadingPanel", "lPanelProps",¨ loadingPanelDepth); // Configure the panel lPanelProps.setTitle("Loading Properties"); lPanelProps.setMessage("0% loaded"); lPanelProps.centerClip(); // Get the size of the properties file totalPropsSize = pm.getBytesTotal(); // Start the event that checks to see if things are loaded root.onEnterFrame = function() { // See how much is loaded currently currentPropsSize = pm.getBytesLoaded(); // Handle if its done or not if(currentPropsSize < totalPropsSize) { // Get percentage percent = (currentPropsSize / totalPropsSize) * 100; percent = Math.round(percent); // Update the message lPanelProps.setMessage(percent + "% loaded"); } else { // Kill the panel lPanelProps.unloadMovie(); // Kill this event _root.onEnterFrame = null; // Start executing again _root.nextFrame(); } } // end onEnterFrame event function propertiesLoaded(success) { // Check to see if it worked if(success) { // get data _global._serverLanguage = this.getProperty¨ ("ServerLanguage"); _global._controllerURL = this.getProperty¨ ("ControllerURL"); 62 // Move to the ShowTopics label gotoAndPlay("ShowTopics"); } else { // Attach the error panel root.attachMovie("ErrorPanel", "propsErrorPanel",¨ errorPanelDepth); // Configure the panel propsErrorPanel.setMessage("Error Loading Properties"); propsErrorPanel.centerClip(); } } // Stop the move from progressing stop();
This code loads the code from the PropertiesManager.as files and dynamically instantiates the loading panel. Once the XML data has been loaded, the ActionScript checks to see if the data properly loaded and either is successful and kills the loading panel or declares that an error loading properties has occurred by displaying the error panel.
Here are the contents of the MBProperties.xml document:
<Properties> <Property> <Name>ServerLanguage</Name> <Value>ASPNET</Value> </Property> <Property> <Name>ControllerURL</Name> <Value>http://msgboard.flashbook.hostingdot.net/¨ TransactionController.aspx/</Value> </Property> </Properties>
The server language is declared and the controller URL is defined for association with proper processing methods that occur later in the system.
Upon success, the application advances to the frame label ShowTopics. Because MBProperties XML data is now loaded, the application can proceed to the loading of topic data. All of the preceding code is processed very rapidly due to Flash MX's ability to quickly parse XML data. .NET is also pre-compiled, which allows for quicker processing of requested data.
Show Topics, Frame 10
On frame 10 on the main Timeline (Figure 3.5), you'll notice that now the message board has taken on the look of a more traditional message board system. Navigation to Home, Register, and Login is available at the top. Remember that viewers can read topics, threads, and responses, but to actively participate they need to first register and then login.
Figure 3.5 Topics data loads in Frame 10.
A ScrollPane with the MC instance name of topicPane resides on the stage (Figure 3.6). It has the following parameters:
Horizontal Scroll = false
Vertical Scroll = auto (auto means you will see a scroll bar if the content fills the area enough to warrant the use of a scroll bar. If this was set to true, you would always see a scroll bar, even when it didn't make sense to have one available.)
Drag Content = false (the pane itself cannot be dragged)
Figure 3.6 The ScrollPane component will contain all the topics data in the system.
The code following areas on the Timeline is very similar in most respects to the code in this section. This is where Flash MX's ability to deploy components, paired with text formatting, really shines.
Populating a ScrollPane with Many Items
The ScrollPane component can only scroll a single item, such as a loaded JPEG image or a movie clip. The message board system actually gets around the problem of loading multiple topic title objects into the ScrollPane for scrolling by actually dynamically creating a single movie clip into the ScrollPane and subsequently populating and associating nested movie clips that contain the textual topics title data.
Take note of the following code on frame 10 (there is a lot of magic that takes place here):
// If the topics are not loaded if(!topicsLoaded) { // Stop the movie stop(); // Attach the loading panel _root.attachMovie("LoadingPanel", "stPanelProps", loadingPanelDepth); // Configure the panel stPanelProps.setTitle("Loading Topics"); stPanelProps.setMessage("0% loaded"); stPanelProps.centerClip(); // set the document to send to the server sd.setDocOut(buildGetTopicsTransaction()); // set the document you want to contain the response sd.setDocIn(new XML()); // set the call back for when its done sd.onLoad = parseTopics; // execute it sd.execute(); // Get the size of the document totalDataSize = sd.getBytesTotal(); // Start the event that checks to see if things are loaded _root.onEnterFrame = function() { // See how much is loaded currently currentDataSize = sd.getBytesLoaded(); // Handle if its done or not if(currentDataSize < totalDataSize) { // Get percentage percent = (currentDataSize / totalDataSize) * 100; percent = Math.round(percent); // Update the message stPanelProps.setMessage(percent + "% loaded"); } else { // Kill this event _root.onEnterFrame = null; // Start executing again _root.nextFrame(); } } // end onLoad event } else { // Load the topics back onto the screen showTopics(); } // end "topicsLoaded" if statement // parseTopics function // This function parses the incoming XML document and // builds the topics list function parseTopics() { // Get the data from the ServerData object var dataIn = this.getDocIn(); // if the transaction worked or not if(!wasSuccessful(dataIn)) { // Attach the error panel _root.attachMovie("ErrorPanel", "topicsErrorPanel", errorPanelDepth); // this goes at the end of the preceding¨ code line // Configure the panel topicsErrorPanel.setMessage(errorMessage); topicsErrorPanel.centerClip(); // Return out of this function return; } // end wasSuccessful() if statement // Create the topics container movie clip _root.createEmptyMovieClip("topics", clipDepth++); dataNode = findDataNode(dataIn); topicsNode = dataNode.firstChild; topicNodes = topicsNode.childNodes; top = 0; width = 660; for(i = 0; i < topicNodes.length; i++) { topicNode = topicNodes[i]; topicChildren = topicNode.childNodes; id = topicNode.attributes.ID; name = topicChildren[0].firstChild.nodeValue; description = topicChildren[1].firstChild.nodeValue; numThreads = topicChildren[2].firstChild.nodeValue; createDate = topicChildren[3].firstChild.nodeValue; backColor = (i % 2)? 0xE9E9E9 : 0xD9D9D9; tempTopic = createTopic(_root.topics, i, width, backColor, id, name, description);// this goes at the end of the¨ preceding // code line tempTopic._y = Math.round(top);// added rounding top += Math.round(tempTopic._height);// added rounding } topicPane.setScrollContent(topics); //topicPane._visible = true; // Kill the panel stPanelProps.unloadMovie(); // Set the topicsLoaded var topicsLoaded = true; } // end parseTopics function // buildGetTopics function // This function builds a 'Get Topics' transaction function buildGetTopicsTransaction() { // Build a basic 'Get Topics' transaction getTopicsRequest = buildBaseRequest("GetTopics"); // Return the xml object return getTopicsRequest; } // end buildGetTopics function // createTopic function // This function creates a single topic in the topics clip¨ function createTopic(container, depth, width, color, id,¨ title, description) {// this goes at the end of the preceding code¨ line name = "topic_" + depth; container.createEmptyMovieClip(name, depth); topic = container[name]; topic.id = id; topic.createTextField("title", 2, 0, 0, width, 0); topic.title.text = title; with(topic.title) { multiline = true; wordWrap = true; border = false; autoSize = "center"; // was center selectable = false; embedFonts = true; } topic.titleformat = new TextFormat(); with(topic.titleFormat) { color = 0xcc0000; // deep red font = "Genetica"; bold = false; leftMargin = 3; // testing size = 10; } topic.title.setTextFormat(topic.titleformat); yPos = topic.title._height + topic.title._x; topic.createTextField("description", 5, 0, yPos, width, 0); // was ("description", 3, 0, yPos, width, 0); topic.description.text = description; with(topic.description) { multiline = true; wordWrap = true; border = false; autoSize = "left"; // was center selectable = false; embedFonts = true; } topic.descriptionformat = new TextFormat(); with(topic.descriptionformat) { color = 0x000000; // black font = "Standard"; bold = false; leftMargin = 3; // testing size = 8; } topic.description.setTextFormat(topic.descriptionformat); height = Math.round(topic._height); height = Math.round(topic._height); topic.createEmptyMovieClip("background", 1); topic.background.color = color; with(topic.background) { beginFill(color); lineTo(width, 0); lineTo(width, height); lineTo(0, height); endFill(); } // Handle topic.background.onRelease = function() { // Hide everything unique to the topics screen _root.hideTopics(); // Set the topic ID _root.topicID = this._parent.id; // Set the topic title _root.topicTitle = this._parent.title.text; // Play click audio _root.click.start(0,0); // Move the playhead to the ShowThreads label _root.gotoAndPlay("ShowThreads"); } // fire this before return topic (since this is temp.¨ reference) topic.background.onRollOver = function(){ _root.click.start(0,0); this._alpha = 30; } topic.background.onRollOut = function(){ this._alpha = 100; } // return the newly created topic return topic; } // end createTopic function // showTopics function // This function shows the already loaded topics again¨ function showTopics() { // Turn the topics clip back on topics._visible = true; // Set the scroll panes contents again topicPane.setScrollContent(topics); } // end showTopics function // hideTopics function // This function hides the topics panel function hideTopics() { // Hide the topics clip topics._visible = false; } // end hideTopics
Because the code is so heavily commented, you should clearly see what's happening in the ActionScript, so I won't cover everything. You'll see the now familiar loading process and also the parsing function for the XML document containing the topics data.
Scan down the code until you come to the line that reads // Create the topics container movie clip. This is where the formatting beauty of Flash MX comes into full play. Following this line, using only ActionScript, an empty movie clip is created with the instance name of "topics".
"But wait, that movie clip isn't associated with the ScrollPane component," you might be thinking to yourself. We take care of that in the code a bit later. We create the empty movie clip, fill it with content, and afterward associate it with the ScrollPane. You'll see this come together in a few minutes.
The XML data is evaluated and the length of XML topics title data is determined, and those titles are then turned into data with movie clips and duplicated one after the other, with alternating background colors. To clarify, here's the code where this actually takes place:
backColor = (i % 2)? 0xE9E9E9 : 0xD9D9D9; tempTopic = createTopic(_root.topics, i, width, backColor,¨ id, name,¨ description); // this goes at the end of the preceding code line tempTopic._y = Math.round(top);// added rounding top += Math.round(tempTopic._height);// added rounding
The rounding has been introduced because the system employs pixel fonts and to maintain their crisp appearance, the interior MCs must reside on integer pixel values (whole numbers.) It's my personal opinion that non-anti-aliased text (like traditional HTML fonts) is ultimately easier to read as body copy. Each developer has his own style and techniques to deploy dynamic data in his applications, but using pixel fonts (you can buy some great ones at www.miniml.com) should greatly benefit your users.
Formatting Text Objects = Power
It's impossible to plan a message board system in which you predetermine the dimensions of dynamic textual objects where multiple data items will be presented. In Flash 5, you had to stack text fields manually or use attachMovieClip to nest textual data together in a semi-presentable fashion. You just didn't know how much text someone was going to enter into certain fields, so you had to take you best guesstimate and hope that the user conformed to your system. Depending on how much content he entered, sometimes your resulting displayed layout would look nice, and other times it could look horrible. With MX, you can now make your system conform to your useryou'll notice that the topics titles are stacked neatly, one atop the other, even if one of the topic titles were to run 3 lines deep. Text objects can now be treated just like a movie clipand that brings with it a lot of customized power. The system can dynamically accommodate entries of any size while maintaining a professionally presentable format. In this way, Flash behaves like traditional HTML tabling, but to a higher and more controllable degree.
The text formatting for the Title text field is achieved with the following ActionScript:
topic.titleformat = new TextFormat(); with(topic.titleFormat) { color = 0xcc0000; // deep red font = "Genetica"; bold = false; leftMargin = 3; // testing size = 10; } topic.title.setTextFormat(topic.titleformat);
The declared font, Genetica, is actually a Linkage name to a font symbol (Genetica) that was created in the Library. In this way, the dynamically created text field can be given a font to associate with it in the display of text data.
Creating a Font Symbol for ActionScript
To create a new font symbol in the Library, from the Library, choose New Font, and you are presented with a dialog box where you give your font symbol a name, choose available fonts loaded on your system, and have a choice of Bold and Italic. The name you give the font symbol does not itself become a Linkage nameit's just a name like those you give to graphics, and so forth. Once you have created a new font symbol in the Library, right-click on the symbol in the Library and choose Linkage. Give the font symbol a Linkage name, and you can choose to export for ActionScript (in first frame or when first encountered), export for runtime sharing, and so on. The identifier you give the symbol enables you to reference and use the font symbol with ActionScript.
With Flash 5 you would need to set the font for a text field (static, dynamic, or input) while authoring. With Flash MX, you can associate a font with text fields created with ActionScript, on-the-fly, as our application does. You could set up multiple fonts for easy OOP implementation. In fact, the topics are set up in the manner. The following code sets the text formatting for the topic title descriptions:
with(topic.descriptionformat) { color = 0x000000; // black font = "Standard"; bold = false; leftMargin = 3; // testing size = 8; } topic.description.setTextFormat(topic.descriptionformat);
The Linkage "Standard" is actually mapped to the actually font Standard 07_53 (Figure 3.7).
Using Different Weights of the Same Font
If you want to use two fonts (such as a normal weight and a bold weight) in one dynamically created text field, you cannot use HTML formatting (<b>)you need to use setTextFormat to do this, combined with format objects.
Figure 3.7 Font Linkage in the Library: The Linkage of the font Standard 07_53 as "Standard"the names need not match as the relationship has already been set in the font symbol itself.
In Flash MX, movie clips can have button events associated with them. In the topics list you see when using the application, you'll notice that rolling over the titles will produce an audio cue and a change in the background color. For each topic title and description, the background is set by dynamically created (drawing API) movie clips with the instance name background. The rollOver is achieved by associated events with the background movie clips like so:
topic.background.onRollOver = function(){ _root.click.start(0,0); this._alpha = 30; } topic.background.onRollOut = function(){ this._alpha = 100; } }
On a rollOver, the function executes by playing the previously instantiated audio object, and reducing the _alpha value of the background clip to 30%. Upon rollOut, the _alpha is set back to 100%. See how much easier and more OOP this is than conventional Flash 5 methods? To play audio in a traditional Flash 5 button, you would need to actually place the audio event within the rollOver state of the button and do the _alpha manipulations by hand. But here we are using a movie clip as a buttoncreated dynamically with ActionScriptand we can easily assign different values for anything to them. This is something Flash 5 simply can't do, and it's very powerful.
To reiterate, we are triggering functions on the button event associations with each background movie clip instance. Macromedia has certainly moved in the right direction with this kind of added functionality (compared to Flash 5). You can dynamically create movie clips now that can be influenced and also serve as a button. That's just another example of how Flash has become much more object-oriented in terms of development.
While the individual topics title containers are being constructed, the topics movie clip is set invisible; once the construction is completed, the movie clip is made visible. This is set up using two functions, one for each state of visibility:
function showTopics() { // Turn the topics clip back on topics._visible = true; // Set the scroll panes contents again topicPane.setScrollContent(topics); } // end showTopics function // hideTopics function // This function hides the topics panel function hideTopics() { // Hide the topics clip topics._visible = false; } // end hideTopics
The topics movie clip is associated with the ScrollPane (instance name of topicPane) with this line of ActionScript:
topicPane.setScrollContent(topics);
In this way the collective set of individual topic titles that are contained inside the topics movie clip can now be scrolled using the ScrollPane component. Remember that the ScrollPane can only manage the manipulation of a single loaded SWF, a movie clip, or JPEG. The code actually allows for the creation of a nested system of individual movie clips to be associated with a single, larger all-encompassing movie clip, which in turn can be manipulated (scrolled up or down) as needed.