1. Trang chủ
  2. » Công Nghệ Thông Tin

Ajax in Action phần 10 pdf

68 346 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

DOM inspectors 583 A.4.1 Using the Mozilla DOM Inspector The DOM Inspector tool is bundled with Firefox but needs to be selected as a cus- tom option during installation. If the DOM Inspector is installed, it will appear in the browser’s menu system under the Tools menu as the option DOM Inspector. When initially opened, the DOM Inspector consists of two panes side by side (fig- ure A.11). The left-hand pane presents a tree-table widget, typically showing only a document and an HTML node initially. The nodes may be opened to reveal a head and body to the document, and within the body, an assortment of nodes representing the HTML markup of a page, plus any elements that have been con- structed programmatically. Where nodes have been assigned ID or CSS class attributes, these will be displayed in additional columns of the tree-table widgets. This tree widget is synchronized to the page being displayed in the main browser window. Selecting a tree node with the mouse will make the related ele- ment in the page layout flash a red border. The relationship is two-way, too. By invoking the Search > Select Element by Click menu option on the DOM Inspec- tor, the user can click on the web browser window and highlight the tree element corresponding to the element clicked upon. (There’s also a toolbar button for this functionality.) The right-hand pane lists information about the current node in one of sev- eral possible formats, including DOM node, CSS style rules, and as a JavaScript object (figure A.12). In the latter mode, the object may be programmatically scripted by right-clicking on the right-hand pane and selecting the Evaluate Java- Script button. The currently selected DOM element can be referred to as target , so, for example, typing in target.style.border='4px solid blue' will outline that element with a thick blue border. Figure A.11 The Mozilla DOM Inspector presents a structural view of the DOM behind a web page, including nodes declared in the HTML and those generated programmatically. Licensed to jonathan zheng <yiyisjun@gmail.com> 584 APPENDIX A The Ajax craftsperson’s toolkit The DOM Inspector also has a third pane, below the other two, into which the vis- ible content of a document can be rendered (figure A.13). If the user types a page address into the URL bar and clicks on the Inspect button, this pane will appear, allowing the abstract DOM and the visible document to be examined side by side. A.4.2 DOM inspectors for Internet Explorer As with all the Mozilla-based toolkits, a major drawback is that the inspectors can’t be used to inspect problems that occur only in Internet Explorer. Several DOM inspectors with similar functionality are available for Internet Explorer. Many are commercial or shareware, but some workable free versions also exist, such as the IEDocMon utility (see the Resources section for URLs). Like the Mozilla DOM Inspector, IEDocMon provides a simple two-pane view of the DOM, with a tree on the left and node details on the right (figure A.13). That concludes our discussions of specific types of development tools. One very active source of Ajax tools is the community that has sprung up around the Firefox browser’s extensions capabilities. In the following section, we’ll briefly outline how to find and install Firefox extensions. Figure A.12 The Mozilla DOM Inspector allows direct scripting access to elements in the DOM. The v ariable name target refers to the currently selected DOM node, in this case the image of the planet, whose border we have just altered. Licensed to jonathan zheng <yiyisjun@gmail.com> Installing Firefox extensions 585 A.4.3 The Safari DOM Inspector for Mac OS X The Mac OS X browser Safari has a built-in DOM inspector too. This is available from the debug menu. The debug menu is not enabled by default. To enable it, open the Terminal application and type in the following: defaults write com.apple.Safari IncludeDebugMenu 1 Depending on your privileges, you may need to sudo this command. Once it has executed, restart Safari and the debug menu should appear. A.5 Installing Firefox extensions We’ve already looked at two very useful Firefox extensions, the Venkman debug- ger and the Live HTTPHeaders network debugger. There are many extensions available for Firefox, and several are designed for use by web developers. In this Figure A.13 The IEDocMon toolbar for Internet Explorer provides functionality similar to the Firefox DOM Inspector, allowing for rapid resolution of rendering issues with programmatically generated user interfaces. Licensed to jonathan zheng <yiyisjun@gmail.com> 586 APPENDIX A The Ajax craftsperson’s toolkit section, we’ll walk briefly through the process of installing a Firefox plug-in, using the Modify Headers extension as an example. Firefox extensions are installed from the web browser itself. Initially, you need to locate the download page for the extension; in this case it’s found at https:// addons.mozilla.org/extensions. The Mozilla add-ons site can also be launched from the browser by clicking the Tools > Extensions menu and then selecting the Get More Extensions link in the pop-up dialog. Figure A.14 shows Firefox point- ing at the Mozilla Update site page for the Modify Headers extension. In this case, the hyperlink we need is the large Install Now button. We click on it, and a dialog appears, warning us of the dangers of installing unsigned exten- sions (figure A.15). Unlike ordinary JavaScript code, extensions have full access to the local file- system. Signing extensions offers a guarantee from the author that the exten- sion hasn’t been tampered with, but in practice, not all extensions are signed. After installation, the extension is registered in the pop-up Extensions dialog (figure A.16). Figure A.14 The Firefox browser lists all installed extensions in a pop-up dialog. More extensions can be installed from the Web. Licensed to jonathan zheng <yiyisjun@gmail.com> Installing Firefox extensions 587 All that remains is to close down all open Firefox windows (including DOM inspectors, debuggers, and so on), and restart Firefox. The extension is then ready to run, appearing as an option in the Tools menu (figure A.17). Firefox supports a large number of extensions, many of which are aimed at web developers. Not all extensions are hosted on the addons.mozilla.org site, but this is certainly the first port of call for such things. The installation procedure is generally similar for all extensions, including the Venkman debugger that we dis- cussed earlier. This concludes our review of development tools for Ajax. We hope that it has provided you with some useful advice in getting your project off the ground. Figure A.15 Firefox extensions can be installed from the Web, using a special downloadable archive format. Figure A.16 Newly installed extensions are visible in the Extensions dialog immediately but won’t become active until the browser is restarted. Licensed to jonathan zheng <yiyisjun@gmail.com> 588 APPENDIX A The Ajax craftsperson’s toolkit A.6 Resources This chapter was all about tools. Here are links to those that we featured: ■ Textpad: www.textpad.com ■ jEdit: www.jedit.org ■ Eclipse: www.eclipse.org ■ Eclipse JavaScript plug-ins: http://jseditor.sourceforge.net/ ■ Visual Studio Express: http://lab.msdn.microsoft.com/express/ ■ Dreamweaver: www.macromedia.com/software/dreamweaver/ ■ Komodo: www.activestate.com/Products/Komodo/ ■ Venkman Debugger: www.mozilla.org/projects/venkman/ ■ Microsoft Script debugger: www.microsoft.com/downloads/details.aspx? Family ID=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en ■ Charles: www.xk72.com/charles/ ■ Fiddler: www.fiddlertool.com ■ LiveHttpHeaders: http://livehttpheaders.mozdev.org/ ■ Modify Headers extension: https://addons.mozilla.org/extensions/more- info.php?id=967&vid=4243 ■ IEDocMon DOM inspector for IE: www.cheztabor.com/IEDocMon/index.htm Figure A.17 After you restart the browser, the extension is ready to use. Licensed to jonathan zheng <yiyisjun@gmail.com> 589 JavaScript for object-oriented programmers Licensed to jonathan zheng <yiyisjun@gmail.com> 590 APPENDIX B JavaScript for object-oriented programmers There are many routes into becoming a JavaScript programmer, ranging from graphic design to a serious programmer coming up from the business tiers. This appendix won’t aim to teach you how to program in JavaScript—there are already many good books and articles to help you do that. What I intend to record here are a few core concepts that will help Java and C# programmers make the leap to JavaScript programming in a relatively painless way. (The same is true to a lesser extent of C++ programmers, but C++ inherits a lot of strange flexibility from C, so that JavaScript should prove less of a shock to the system.) If you are a serious enterprise programmer with a grounding in OO design principles, then your first approaches to JavaScript may be overly influenced by your experience with languages such as Java and C#, and you may find yourself fighting against the language rather than working with it. I certainly did, and I’ve based this on my own experience as a programmer and in mentoring others along the same route. JavaScript can do a lot of clever things that Java and C# can’t. Some of these can help you to write better code, and some can only help you to shoot yourself in the foot more accurately! It’s worth knowing about both, either to make use of the techniques or to avoid doing them unwittingly. If you are coming to Ajax from a structured OO language such as Java or C++, then I hope that reading this appen- dix will help you as much as I think it would have helped me a few years back! B.1 JavaScript is not Java What’s in a name? In the case of Java and JavaScript, a lot of marketing and rel- atively little substance. JavaScript was renamed from “livescript” at the last minute by Netscape’s marketing department, and now the name has stuck. Con- trary to popular perception, JavaScript is not a descendent of the C family of lan- guages. It owes a lot more to functional languages such as Scheme and Self, and it has quite a lot in common with Python, too. Unfortunately, it’s been named after Java and syntactically styled to look like Java. In places, it will behave like Java, but in many places, it just plain won’t. Table B.1 summarizes the key differences. Table B.1 Key features of JavaScript and their implications Feature Implications Variables are loosely typed. Variables are just declared as variables, not as integers, strings, or objects of a specific class. In JavaScript, it is legal to assign values of different types to the same variable. continued on next page Licensed to jonathan zheng <yiyisjun@gmail.com> JavaScript is not Java 591 These differences allow the language to be used in different ways and open up the possibility of a number of weird tricks worthy of a seasoned Lisp hacker. If you’re a really clever, disciplined coder, you can take advantage of these tricks to do mar- velous things, and you might even do so beyond a few hundred lines of code. If, on the other hand, you only think you’re really clever and disciplined, you can quickly end up flat on your face. I’ve tried it a few times and come to the conclusion that keeping things simple is generally a good thing. If you’re working with a team, coding standards or guide- lines should address these issues if the technical manager feels it is appropriate. However, there is a second reason for knowing about these differences and tricks: the browser will use some of them internally, so understanding what is going on can save you much time and pain in debugging a badly behaved applica- tion. In particular, I’ve found it helpful to know where the code is not behaving like a Java object would, given that much of the apparent similarity is only apparent. So read on, and find out what JavaScript objects really look like when the lights are out, how they are composed of member fields and functions, and what a JavaScript function is really capable of. Code is dynamically interpreted. At runtime, code is stored as text and interpreted into machine instructions as the program runs, in contrast to precompiled lan- guages such as Java, C, and C#. Users of your website can gener- ally see the source code of your Ajax application. Furthermore, it allows for the possibility of code being generated dynamically by other code without resorting to special bytecode generators. JavaScript functions are first-class objects. A Java object’s methods are tied to the object that owns them and can be invoked only via that object. JavaScript functions can be attached to objects so that they behave like methods, but they can also be invoked in other contexts and/or reattached to other objects at runtime. JavaScript objects are prototype-based. A Java, C++, or C# object has a defined type, with superclasses and virtual superclasses or interfaces. This strictly defines its func- tionality. Any JavaScript object is just an object, which is just an associative array in disguise. Prototypes can be used to emulate Java-style types in JavaScript, but the similarity is only skin deep. Table B.1 Key features of JavaScript and their implications (continued) Feature Implications Licensed to jonathan zheng <yiyisjun@gmail.com> 592 APPENDIX B JavaScript for object-oriented programmers B.2 Objects in JavaScript JavaScript doesn’t require the use of objects or even functions. It is possible to write a JavaScript program as a single stream of text that is executed directly as it is read by the interpreter. As a program gets bigger, though, functions and objects become a tremendously useful way of organizing your code, and we recommend you use both. The simplest way to create a new JavaScript object is to invoke the built-in con- structor for the Object class: var myObject=new Object(); We’ll look at other approaches, and what the new keyword really does, in sec- tion B.2.2. Our object myObject is initially “empty,” that is, it has no properties or methods. Adding them in is quite simple, so let’s see how to do it now. B.2.1 Building ad hoc objects As already noted, the JavaScript object is essentially just an associative array, with fields and methods keyed by name. A C-like syntax is slapped on top to make it look familiar to C-family programmers, but the underlying implementation can be exploited in other ways, too. We can build up complex objects line by line, add- ing new variables and functions as we think of them. There are two ways of building up objects in this ad hoc fashion. The first of these is to simply use JavaScript to create the object. The second is to use a special notation known as JSON. Let’s start with the plain old JavaScript technique. Using JavaScript statements In the middle of a complicated piece of code, we may want to assign a value to some object’s property. JavaScript object properties are read/write and can be assigned by the = operator. Let’s add a property to our simple object: myObject.shoeSize="12"; In a structured OO language, we would need to define a class that declared a property shoeSize or else suffer a compiler error. Not so with JavaScript. In fact, just to emphasize the array-like nature, we can also reference properties using array syntax: myObject['shoeSize']="12"; This notation is clumsy for ordinary use but has the advantage that the array index is a JavaScript expression, offering a form of runtime reflection, which we’ll return to in section B.2.4. Licensed to jonathan zheng <yiyisjun@gmail.com> [...]... or, indeed, any JavaScript Object: myLibrary.books["BestSeller"]=somePredefinedBook; This syntax is good for fine-tuning, but building a large array or object in the first place can be tedious The shorthand for creating a numerically indexed array is to use square braces, with the entries being written as a comma-separated list of values, thus: myLibrary.books=[predefinedBook1,predefinedBook2,predefinedBook3];... predefinedBook1, cookbook : predefinedBook2, spaceFiller : predefinedBook3 }; In both notations, extra white space is ignored, allowing us to pretty-print for clarity Keys can also have spaces in them, and can be quoted in the JSON notation, for example: "Best Seller" : predefinedBook1, We can nest JSON notations to create one-line definitions of complex object hierarchies (albeit rather a long line):... working with that, you’ll soon be familiar with the idiom Functions become really interesting, though, when we take advantage of their independence as first-class objects B.3.2 Attaching functions to objects As a functional language, JavaScript allows us to define functions in the absence of any object, for example: function doSomething(x,y,z){ } Functions can also be defined inline: var doSomething=function(x,y,z){... Objects in JavaScript 597 B.2.2 Constructor functions, classes, and prototypes In OO programming, we generally create objects by stating the class from which we want them to be instantiated Both Java and JavaScript support the new keyword, allowing us to create instances of a predefined kind of object Here the similarity between the two ends In Java, everything (bar a few primitives)... the point of view of objects Now let’s drill down a little to look at these functions that we’ve been throwing around and see what they really are B.3 Methods and functions We’ve been defining functions and calling them in the previous section and in the rest of this book A Java or C# programmer might have assumed that they were something like a method, defined with a slightly funny-looking syntax In. .. class definition.) Programmers who have worked their way through the C family may think “Ah, so it’s like a function pointer in C++, then.” It is indeed, but that’s not the end of it In JavaScript, Function is a type of built -in object As expected, it contains executable code, and can be invoked, but it is also a descendant of Object, and can do everything that a JavaScript object can, such as storing properties... with a concise mechanism for creating this information in a single pass, something that would otherwise have taken many lines of code (and greater bandwidth) Sharp-eyed readers will have noted that we populated the publication date for the second book using a JavaScript Date object In assigning the value we can use any JavaScript code, in fact, even a function that we defined ourselves: function gunpowderPlot(){... myObj.doSomethingNew(x,y,z); We can also attach functions such that every instance of a class can access them, by adding the function (either predefined or declared inline) to the new object in the constructor, as we saw in section B.2.2, or by attaching it to the prototype Once we’ve done this, though, they aren’t very strongly attached, as we will see B.3.3 Borrowing functions from other objects Giving functions... language in this appendix, with two purposes in mind The first was to show the expressive power of the language The second was to point out several traps for the unwary, in which thinking in an OO style may result in suboptimal or even dangerous code We’ve looked at JavaScript’s support for objects and at the similarities between the Object and Array classes We’ve seen several ways of instantiating JavaScript... of a Shape-processing library doesn’t need to consider the specific implementations, and the author of a new implementation of Shape doesn’t need to consider the internals of any library code or any other existing implementations of the interface Interfaces provide good separation of concerns and underpin many design patterns If we’re using design patterns in Ajax, we want to use interfaces JavaScript . be installed from the Web. Licensed to jonathan zheng <yiyisjun@gmail.com> Installing Firefox extensions 587 All that remains is to close down all open Firefox windows (including DOM inspectors,. DOM inspectors 583 A.4.1 Using the Mozilla DOM Inspector The DOM Inspector tool is bundled with Firefox but needs to be selected as a cus- tom option during installation. If the DOM Inspector. reason for knowing about these differences and tricks: the browser will use some of them internally, so understanding what is going on can save you much time and pain in debugging a badly behaved

Ngày đăng: 09/08/2014, 12:22

Xem thêm: Ajax in Action phần 10 pdf