Flash Builder 4 and Flex 4 Bible- P5
lượt xem 21
download
Flash Builder 4 and Flex 4 Bible- P5: 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....
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: Flash Builder 4 and Flex 4 Bible- P5
- Chapter 6: Debugging Flex Applications FIGURE 6.4 The Console view Preferences dialog box Terminating a debugging session You should always explicitly terminate a debugging session before trying to run or debug an appli- cation again. You can terminate a debugging session in many ways: l Choose Run ➪ Terminate from the Flash Builder menu. l As shown in Figure 6.5, click the square red Terminate button in the Console view. l Click the square red Terminate button in the Debug view (visible in the Flex Debugging perspective). l Close the browser in which the application is running (for a Web application). l Close the application (for a desktop application). Tip When you terminate a Web application’s debugging session from within Flash Builder, the browser sometimes closes automatically, depending on which Web browser and operating system you’re using and whether any other tabs or browser windows are open. For example, provided that no other sites are open, Internet Explorer and Firefox on Windows always close automatically. Firefox on the Mac doesn’t always close automatically. The fact that this behavior differs from one operating system to another is not a cause for concern. n 171
- Part I: Flex Fundamentals FIGURE 6.5 The Console view’s Terminate button The Terminate button Using trace() and the Logging API With Flex, you can generate and send logging messages to Flash Builder and other logging targets at runtime. Tracing is typically useful when you’re trying to get runtime information about the following: l Variable values l The order of application execution l Whether various bits of code are being executed as expected In its simplest use, logging is accomplished through use of the trace() method. More advanced logging techniques are also available through an interface known as the Logging API. Using the trace() function The trace() function is global to Flash Player; that is, it’s always available without your having to reference or import an ActionScript class. The purpose of the trace() function is to send a text message to a logging target. In its simplest form, trace is called with a String value: trace(‘A tracing message’); You also can pass in variables and concatenated expressions that can result in a String: trace(“The value of myVariable is “ + myVariable); In fact, any object that can serialize to a String can be passed to trace(). In this example, an Array of String values is passed to trace(): trace([‘hello’, ‘world’]); Because the Array class is automatically serialized as a comma-delimited string, the resulting out- put message looks like this: hello,world 172
- Chapter 6: Debugging Flex Applications Trace messages in Flash Builder’s Console view When you debug a Flex application with Flash Builder, the value you pass into trace() is displayed in Flash Builder’s Console view. Tip Calls to trace() are ignored when you run, rather than debug, an application even though the same debug version of your application is being executed. These calls are also stripped from an application’s release version, so you can leave any calls to trace() in an application without affecting runtime performance or file size. n Try these steps to see the trace() function at work: 1. Create a new Flex application with the following code: 2. Click Debug, or press F11 (Windows) or Ô+F11 (Mac), to debug the application. 3. Click Call Trace in the application to call trace(). 4. Switch back to Flash Builder, and look at the Console view. As shown in Figure 6.6, you should see the tracing message displayed in the Console view. FIGURE 6.6 A tracing message in the Console view Tracing message in the Console view Sending tracing messages to flashlog.txt Messages also can be saved to a text file named flashlog.txt. The flashlog.txt file is cre- ated by the debugger version of Flash Player in a particular folder on your system. 173
- Part I: Flex Fundamentals Configuring Flash Player with mm.cfg You configure the use of flashlog.txt with another text file named mm.cfg. This file contains parameters that control what messages are sent to, and saved in, the file. The location of mm.cfg differs by operating system. Table 6.1 shows the location for each operating system that’s supported by Flash Player. TABLE 6.1 Location of mm.cfg Operating System Location Macintosh OS X /Library/Application Support/Macromedia Windows 95/98/ME %HOMEDRIVE%\%HOMEPATH% Windows 2000 & XP C:\Documents and Settings\username Windows Vista & 7 C:\Users\username Linux /home/username To save both error reporting and tracing messages to the flashlog.txt file, add these parameters on their own separate lines in mm.cfg: ErrorReportingEnable=1 TraceOutputFileEnable=1 After these settings have been created, the next time you debug a Flex application or Flash docu- ment, the flashlog.txt is created automatically. Each time you call trace(), the message is saved to the file, in addition to being sent to Flash Builder’s Console view. Location of flashlog.txt The flashlog.txt file is placed in a particular location that differs by operating system. Table 6.2 shows the location of flashlog.txt for each operating system on which Flash Player is supported. TABLE 6.2 Location of flashlog.txt Operating System Location Macintosh OS X /Users/username/Library/Preferences/Macromedia/ Flash Player/Logs Windows 95/98/ME/2000/XP C:\Documents and Settings\username\ Application Data\Macromedia\Flash Player\Logs Windows Vista & 7 C:\Users\username\AppData\ Roaming\Macromedia\Flash Player\Logs Linux /home/username/.macromedia/Flash_Player/Logs 174
- Chapter 6: Debugging Flex Applications Tip Both mm.cfg and flashlog.txt are simple text files and can be viewed and edited with any text editor. n Using the Logging API The Logging API is an advanced architecture that enables you to filter logging messages that are generated by the Flex Framework, and send messages to a logging target of your choice. The Logging API consists of an ActionScript interface named ILogger, a class that implements ILogger named LogLogger, a singleton class named Log, and a predefined tracing target class named TraceTarget. You can extend the API (application programming interface) by creating your own versions of ILogger implementations and tracing targets, but you also can make very good use of the API with just these pre-built components. Tip ActionScript 3 enables developers to use interfaces to define the required elements of a class definition. An interface isn’t the same thing as a class. For example, it doesn’t implement any code in its method definitions, and you can’t create an instance of an interface directly. Its purpose is to establish a contract that must be fulfilled by any classes that claim to implement its members. In the Flex framework, interfaces are always named within an initial uppercase I, followed by a descriptive name. For example, the interface named ILogger can be described simply as “the Logger interface.” n Using the Log class You get started with the Logging API by creating a Logger object using the Log class’s static getLogger() method. You can create custom logger objects that are sensitive to particular cate- gories of events, and you can automatically include that category information in logging messages. The syntax for getLogger() is: private var myLogger:ILogger = Log.getLogger(“myCategory”); The category you pass into getLogger() must be a nonblank string. If the category you provide is registered by an existing class that implements ILogger, you get an instance of that class. Otherwise, you get an instance of a class named mx.logging.LogLogger that implements basic logging functions. The Logging API supports these levels, in ascending order of panic: l ALL l DEBUG l INFO l WARN l ERROR l FATAL 175
- Part I: Flex Fundamentals The Log class implements these methods that enable you to determine whether a logging target has been defined for various logging levels: l isDebug():Boolean l isInfo():Boolean l isWarn():Boolean l isError():Boolean l isFatal():Boolean Using Logger objects A logger class implements the ILogger interface. The interface includes these methods to send messages to a logging target: l debug(message:String, ... rest):void l error(message:String, ... rest):void l fatal(message:String, ... rest):void l info(message:String, ... rest):void l warn(message:String, ... rest):void l log(level:int, message:String, ... rest):void After you’ve created a logger object, you send a logging message with one of the previous methods. Most methods create a message with a specific logging level. For example, to send a message with a level of DEBUG, you call the logger object’s debug() method: myLogger.debug(“My debug message”); The debugging levels are defined as constants in a class named mx.logging.LogEventLevel. You also can send logging messages with the logger object’s log() method and explicitly pass in the appropriate level: myLogger.log(LogEventLevel.DEBUG, “My debug message”); Tip The use of the LogEventLevel class’s constants to select a logging level is considered a best practice. As with event names, any typos in the names of the constants result in compiler errors, as opposed to runtime errors or silent failures that you may encounter when using simple strings. n Logging levels are used to filter which messages are handled by various logging targets. Self-logging components The Logging API can be used to create a self-logging component. For example, the application in Listing 6.1 is a Button component that logs each click event to a logging target. 176
- Chapter 6: Debugging Flex Applications LISTING 6.1 A self-logging button component On the Web The code in Listing 6.1 is available in the Web site files in the chapter06 project’s debug package as LoggingButton.mxml. n Cross-Reference The code sample in Listing 6.1 uses the Flex event model to handle component events. The event model is described in Chapter 7. n Using tracing targets A tracing target is a class that can receive and process tracing messages. The TraceTarget class is included in the Flex Framework and is ideally suited to use in Flex applications. When you use the TraceTarget class, the output of the Logging API behaves just like output you create with the trace() method. The messages appear in Flash Builder’s Console view and, if you’ve configured Flash Player as described previously, are saved in flashlog.txt. The TraceTarget class supports these properties: l fieldSeparator:String. A string value to separate other values included in a logging message; defaults to a single space character. l includeCategory:Boolean. Indicates whether to include the logging message’s category in the logging message. 177
- Part I: Flex Fundamentals l includeDate:Boolean. Indicates whether to include the current date in the logging message. l includeLevel:Boolean. Indicates whether to include the logging level in the logging message. l includeTime:Boolean. Indicates whether to include the current time in the logging message. l level:int. A logging level that this target will handle; defaults to LogEventLevel.ALL. You can instantiate TraceTarget with either MXML or ActionScript. Use this syntax to instanti- ate the class in its simplest form: New Feature In Flex 4, the element must be placed inside the element, along with other nonvisual object declarations: n Caution The Declarations tag uses the fx prefix, because it’s a core part of MXML. The TraceTarget tag can use either the mx or the s prefix, because although it’s part of the Flex 3 class library, it’s registered in the mani- fests for both the older MX and the new Spark component sets. n Tip The MXML declaration does not require an id property. Unless you need to call its methods or properties directly, the object can be declared anonymously. n In its default form, TraceTarget becomes a tracing target that handles all logging levels. However, the tracing messages you see include only the messages themselves and none of the other available logging data such as date, time, level, and category. Use this syntax to include all that information and separate the data elements from each other with a | (pipe) character: Finally, to make a tracing target display messages only for a particular logging level, use this syntax: 178
- Chapter 6: Debugging Flex Applications Caution In the last example, the LogEventLevel class would have to be imported before being referenced in the TraceTarget.level binding expression: import mx.logging.LogEventLevel; n The resulting trace output generated by the self-logging button component in Listing 6.1 would look like this: 5/17/2009|21:43:44.051|[DEBUG]|buttonEvents|LoggingButton myLoggingButton was clicked The application in Listing 6.2 uses the self-logging button and a TraceTarget object. The TraceTarget object is configured only to handle messages with a logging level of DEBUG and to include all available information in each message. LISTING 6.2 An application with a self-logging component On the Web The code in Listing 6.2 is available in the Web site files in the chapter06 project folder as UseLogging Button.mxml. n 179
- Part I: Flex Fundamentals The Logging API can enable you to build applications that keep you informed about their actions during a debugging session without having to make constant calls to the trace() method. With some advanced ActionScript programming, you also can create your own custom logger and trac- ing target classes. Using Breakpoints A breakpoint enables you to suspend application execution at runtime and inspect the applica- tion’s current state. Once you’re in a breakpoint, you can look at variable values, evaluate arbitrary ActionScript expressions, and take other actions that help you figure out what’s happening. Setting and clearing breakpoints Breakpoints can be set on any line that includes at least one ActionScript statement. For example, this code declares a button component but has no ActionScript code: If you set a breakpoint on the line containing that MXML declaration and then run the application in debug mode, the breakpoint icon changes to display a little red X to indicate that it will be ignored by the debugger. If you then hover the mouse cursor over the breakpoint while the application is sus- pended, Flash Builder displays a tooltip saying that you can’t put a breakpoint in that location. If, however, the same MXML declaration includes an event handler that executes some ActionScript code, it becomes a valid target for a breakpoint: Because this version of the declaration executes an ActionScript statement, placing a breakpoint on that line successfully suspends the application when the user clicks the button. Setting and removing breakpoints in an MXML or ActionScript editor You can set or remove a breakpoint in an MXML or ActionScript editor. To do so, perform one of these actions: l Place the cursor on the line where you want the breakpoint, and press Ctrl+Shift+B (Windows) or Ô+Shift+B (Mac). l Double-click the line number in the editor. l As shown in Figure 6.7, right-click the line number in the editor, and select Toggle Breakpoint. As shown in Figure 6.8, the breakpoint appears as a small dot to the left of the line number. 180
- Chapter 6: Debugging Flex Applications FIGURE 6.7 Right-click a line number to see this context menu, and select Toggle Breakpoint. FIGURE 6.8 A Breakpoint represented by a small icon next to a line number A breakpoint Setting conditional breakpoints Each breakpoint has a set of properties you can configure to determine when the breakpoint is triggered. New Feature Conditional breakpoints are a new feature of Flash Builder 4. n 181
- Part I: Flex Fundamentals You can set the following properties on each individual breakpoint: l Enabled. A Boolean value indicating whether the breakpoint will be respected. l Hit Count. A positive integer that indicates you only want to suspend the application when the breakpoint is hit the nth time. l Enable Condition. An ActionScript expression. If it’s a Boolean expression, it can be used to suspend the application only when the condition is true. Otherwise, use it to suspend the application only when the expression’s value changes. You can set breakpoint properties either from an MXML or ActionScript editor or from the Breakpoints view. Follow these steps: 1. After creating a breakpoint in an ActionScript or MXML editor, right-click (or Ctrl+click on Mac) on the breakpoint icon next to the line number. 2. Select Breakpoint Properties from the context menu. 3. As shown in Figure 6.9, set the breakpoint properties. For example, if you only want to suspend the application when a variable named myVar has a value of 3, select Enable Condition and then type this expression in the text box: myVar==3 4. Click OK. FIGURE 6.9 The Breakpoint Properties dialog box 182
- Chapter 6: Debugging Flex Applications Caution When setting a conditional breakpoint to be triggered only when a comparison of two values returns true, make sure you use the double-equals (==) comparison operator in the expression, rather than the single-equals (=) assignment operator. n Using the Breakpoints view Flash Builder’s Breakpoints view shows you the application’s current breakpoints and enables you to add, remove, enable, or disable breakpoints as needed. The Breakpoints view is displayed in the Flex Debugging perspective. To use the Breakpoints view, follow these steps: 1. Choose Window ➪ Perspective ➪ Flex Debugging from the Flash Builder menu. 2. Click the Breakpoints tab in the upper-right corner of the Flash Builder interface. The Breakpoints view, shown in Figure 6.10, displays all breakpoints for the current project. FIGURE 6.10 The Breakpoints view Remove all Go to file Remove Selected Skip all Breakpoints The Breakpoints view includes these tools: l Remove. Removes the currently selected breakpoint. l Remove All. Removes all breakpoints in the current project. l Show Breakpoints. Supported by Selected Target; shows breakpoints only for a selected debug target. l Go to File for Breakpoint. Opens file for current breakpoint and moves cursor to that position. l Skip All Breakpoints. Causes debugging session to ignore breakpoints. Click the appropriate button to use any of the tools listed previously. The Remove All Breakpoints tool requires you to confirm the operation. 183
- Part I: Flex Fundamentals Exporting breakpoints to an external file The Breakpoints view enables you to export and import breakpoint definitions to external files. A breakpoints file has a file extension of .bkpt. Follow these steps to export breakpoints: 1. Right-click anywhere in the Breakpoints view, and select Export Breakpoints from the context menu. 2. In the Export Breakpoints dialog box, shown in Figure 6.11, select the following: l Which breakpoints you want to export l The file to which you want to export breakpoints l The Overwrite existing file without warning check box (if you want to overwrite your existing file) FIGURE 6.11 The Export Breakpoints dialog box 3. Click Finish to create the breakpoints file. A breakpoints export file is in XML format. Listing 6.3 shows the contents of a typical breakpoints file. 184
- Chapter 6: Debugging Flex Applications LISTING 6.3 An exported breakpoints file Importing breakpoints from an external breakpoint file Follow these steps to import an external breakpoints file: 1. Right-click anywhere in the Breakpoints view, and select Import Breakpoints from the context menu. 2. In the Import Breakpoints dialog box, shown in Figure 6.12, select these options, if appropriate: l Whether you want to update existing breakpoints l Whether you want to automatically create breakpoint working sets 3. Click Finish to import the breakpoints file. The breakpoints in the external file are imported and are immediately available in the Breakpoints view. Using breakpoints in a debugging session After you’ve set breakpoints, you can use them during a debugging session by executing the code on which the breakpoints are set. When an application is running in debug mode and is suspended at a breakpoint, Flash Builder tries to take system focus. If you are not currently using the Flex Debugging perspective, the Confirm Perspective Switch dialog box, shown in Figure 6.13, prompts you to switch to that perspective. 185
- Part I: Flex Fundamentals FIGURE 6.12 Importing a breakpoints file FIGURE 6.13 When a breakpoint has been activated, you’re prompted to open the Flex Debugging perspective with the Confirm Perspective Switch dialog box. Tip The Confirm Perspective Switch dialog box has an option that enables you to remember the decision to switch to the Flex Debugging perspective when you encounter a breakpoint. If you select this option, Flash Builder always switches to this perspective automatically in future uses of breakpoints. You can turn this on and off by selecting an option in the Run/Debug section of Flash Builder’s Preferences dialog box. n After a breakpoint has been activated, Flash Builder shows you the current code execution position with the Debug Current Instruction Pointer, shown in Figure 6.14. If you move the cursor over the pointer icon, you see a pop-up window displaying information about the current line. 186
- Chapter 6: Debugging Flex Applications FIGURE 6.14 The Debug Current Instruction Pointer and current line information Inspecting variables and expressions When a breakpoint is active during a debugging session, Flash Builder enables you to inspect values of variables and objects that are in the application’s scope. You can use two views for this purpose: l The Variables view l The Expressions view Using the Variables view The Variables view displays a tree of declared variables and object properties that are in scope at the point of the current instruction. Information in the Variables view is available only during a breakpoint; when you resume application execution, the Variables view no longer displays data. The Variables view always has a tree item labeled this. The item refers to the application when the currently executing code is in the Application scope, or to the current component or class when the currently executing code is in that scope. As shown in Figure 6.15, when you click the expansion icon with the + character next to this, you see a list of all properties of the application or current object. A tree item representing an object has an inherited branch that displays properties declared in the current object’s inheri- tance hierarchy. Note Flex Builder 3 added the inherited branch to separate properties that are declared within the current class from those declared in its superclasses. n Tip The Variables tree is recursive; that is, you can click down to any object within the application, and then click the inherited ➪ $parent item under the button and return to the Application object. n 187
- Part I: Flex Fundamentals FIGURE 6.15 The Variables view When you place a breakpoint inside a function, the Variables view displays tree items for any vari- ables that are declared within the function. For example, the following code declares a variable named myVar data typed as a Number: private function myFunction():void { var myVar:Number=1; } //place breakpoint here When you stop code execution with a breakpoint on the function’s final line, the resulting Variables view displays the value of myVar as 1, as shown in Figure 6.16. Setting watchpoints A watchpoint is an instruction to suspend the application at runtime when a particular variable’s value changes. New Feature Watchpoints are a new feature of Flash Builder 4. n 188
- Chapter 6: Debugging Flex Applications FIGURE 6.16 Displaying a local variable in the Variables view A local variable You set watchpoints in the Variables view while the application is already suspended. You can set watchpoints on these types of variables: l A variable set outside any functions as a property of the current application or module l A property of a complex object declared locally within a function You cannot set watchpoints on these types of variables: l Local variables defined within a function l Implicit getter functions that use the get keyword Caution Watchpoints are removed when the current debugging session is terminated. If you want to set them again, do so after suspending the application at a breakpoint. n The application in Listing 6.4 triggers a breakpoint in one method and changes a variable value in another. LISTING 6.4 An application that can be used to trigger a watchpoint
- Part I: Flex Fundamentals LISTING 6.4 (continued) private var xyz:String; protected function breakpointButton_clickHandler( event:MouseEvent):void { trace(‘debug’); } protected function watchpointButton_clickHandler( event:MouseEvent):void { xyz=’New Value’; } ]]> On the Web The code in Listing 6.4 is available in the Web site files in the chapter06 project as UseWatchpoint.mxml. n Follow these steps to use a watchpoint: 1. Create a breakpoint at a line containing an ActionScript statement, such as the call to trace() in Listing 6.4. 2. Run the application in debug mode and take whatever action is required to trigger the breakpoint. 3. Open the Variables view in the Debugging perspective. 4. Locate the variable you want to watch. 5. Right-click on the variable and select Toggle Watchpoint. 6. Open the Debug view and resume the application. 7. Take an action that results in changing the variable, such as the second function in Listing 6.4. You should see that Flash Builder suspends the application right after the line of code that changed the variable value. Your changed variable, along with any other changed variables, should be high- lighted to yellow in the Variables view. Tip If you trigger a watchpoint as a result of inline ActionScript code inside an MXML event listener, such this: click=”xyz=’New Value’” 190
CÓ THỂ BẠN MUỐN DOWNLOAD
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn