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

Dreamweaver MX 2004 Bible phần 10 pptx

121 336 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

Nội dung

1063 Chapter 34 ✦ Creating a Behavior built-in functions. The Extending Dreamweaver documentation can be found by choosing Help ➪ Extending Dreamweaver. Although Extending Dreamweaver covers all types of Dreamweaver extensions, behavior developers are interested in three main sections: the Dreamweaver Document Object Model, the Dreamweaver JavaScript API, and Behaviors. If your behavior is intended to interact with Fireworks, you want to study the Fireworks Integration API section. The more you understand about the various components and their included functions, the more flexibility you have in building your behaviors. The material in this section is intended for programmers familiar with JavaScript and, as such, is fairly advanced. Document Object Model JavaScript is an interpreted programming language that addresses elements in the browser and on the Web page in a hierarchical fashion. To access the properties of any object on the page, JavaScript employs a Document Object Model (DOM). The DOM breaks down the page into successively smaller parts until each element and its specific properties are identified. Dreamweaver MX 2004 integrates a subset of objects, properties, and methods from the W3C DOM Level 1 with a subset of properties from the Internet Explorer 4.0 DOM. The resultant Dreamweaver DOM also includes some useful features not implemented in either of the other DOMs. Understanding nodes Dreamweaver’s DOM makes available, or exposes, virtually every element on a Web page. The DOM is often described using a tree metaphor, with the HTML document as the trunk. Instead of regarding the <head> and the <body> as the major branches, however, Dreamweaver’s DOM, like the W3C DOM, uses four separate branches, or nodes, to divide the document: ✦ DOCUMENT_NODE: Enables access to objects directly relating to the overall document ✦ ELEMENT_NODE: Contains references to all tags in the HTML document ✦ TEXT_NODE: Describes the contiguous block of text within tags ✦ COMMENT_NODE: Represents the comments within an HTML document and the text strings they contain Just as one tree branch can lead to another, nodes can contain other nodes. For example, a layer can contain a table that holds table rows that, in turn, hold table data. One node con- taining another is said to be in a parent-child relationship, and a node that cannot contain any other nodes is referred to as a leaf node because it is incapable of supporting any more branches. Figure 34-3 illustrates the node concept. DOM properties When referencing a specific tag, the DOM syntax goes from the most general to the most spe- cific. For example, suppose you want to find out what a user entered into a specific text field, a property called value. You need to start from the document itself and work your way down through the form and text box objects, as follows: var theText = document.formName.textboxName.value; Caution 543504 ch34.qxd 12/10/03 10:43 PM Page 1063 1064 Part VII ✦ Extending Dreamweaver Figure 34-3: Nodes are used to express the structure of the HTML document and its relationship to the browser. The DOM dictates what properties are accessible and in what form. Not all properties and methods are supported. You can’t, for instance, directly reference the value of a button in a form. Instead, you have to assign that value to a hidden or other text field and access that value. The portion of the DOM relating directly to forms and form elements is discussed in Chapter 33. The same rules of use and the same restrictions for implementing forms in objects apply, like- wise, to implementing forms in behaviors. Additionally, the Dreamweaver DOM addresses other major objects as outlined in Table 34-1. Read-only properties are marked with an aster- isk (*); otherwise, properties can be both read and set. Cross- Reference BODY DOCUMENT TEXT DATA COMMENTS ELEMENTS TABLES FORMS 543504 ch34.qxd 12/10/03 10:43 PM Page 1064 1065 Chapter 34 ✦ Creating a Behavior Table 34-1: Dreamweaver DOM Properties Property Nodes Returns Description nodeType* all Node.DOCUMENT_NODE Returns the node of the Node.ELEMENT_NODE specified selection Node.TEXT_NODE Node.COMMENT_NODE parentNode* all string (HTML tag), Returns null or the document object, or null fdocument object; returns the parent tag for element, text, and comment objects; if an HTML tag is selected, returns the document object parentWindow* DOCUMENT_NODE parent window object Returns the JavaScript object corresponding to the document’s parent window childNodes* all NodeList Returns a NodeList array of the immediate children of the current selection documentElement* DOCUMENT_NODE HTML tag of current Returns the JavaScript document object corresponding to the HTML tag of the current document body* DOCUMENT_NODE BODY tag of current Returns the JavaScript document object corresponding to the BODY tag of the current document URL* DOCUMENT_NODE file://URL Returns the file://URL for the current document tagName* ELEMENT_NODE IMG Returns the HTML name TABLE (in CAPS) for the current tag attrName ELEMENT_NODE grey Returns the value of the #33CC66 specified tag attribute innerHTML ELEMENT_NODE for <p>Hello Returns the HTML source <i>world!</i></p> for a tag, without the tag p.innerHTML would code itself return: Hello <i>world!</i> Continued 543504 ch34.qxd 12/10/03 10:43 PM Page 1065 1066 Part VII ✦ Extending Dreamweaver Table 34-1 (continued) Property Nodes Returns Description outerHTML ELEMENT_NODE for <p>Hello Returns the HTML source <i>world!</i></p> or a tag, including the tag p.outerHTML would fcode return: <p>Hello <i>world!</i></p> data TEXT_NODE “J. Lowery” where the tag Returns the text string COMMENT_NODE reads <p>J. Lowery</p> contained within a contiguous block of text or a comment * Read-only DOM methods Methods, in programming, are functions attached to a particular object, such as the document object. Dreamweaver includes several methods in the DOM to help manipulate the HTML page. With the node structure, you can apply these methods to the current document, frame- set, frame, or selected object. Using these methods, your behaviors can inspect the current page and, if desired, change or even delete any attributes found. Table 34-2 outlines the methods contained in the Dreamweaver DOM. Table 34-2: Dreamweaver DOM Methods Method Nodes Returns Description hasChildNodes()* all true or Determines if current false selection has children getElementsByTagName DOCUMENT_NODE NodeList Returns a NodeList (tagName) ELEMENT_NODE array of all instances of the specified tag on the current page getTranslatedAttribute(attrName) ELEMENT_NODE string or Gets the translated null value of the specified attribute; used in conjunction with Dreamweaver translators hasTranslatedAttributes() ELEMENT_NODE true or Determines if the tag false has translated attributes; used in conjunction with Dreamweaver translators getAttribute(attrName) ELEMENT_NODE string or Gets the value of the null specified attribute 543504 ch34.qxd 12/10/03 10:43 PM Page 1066 1067 Chapter 34 ✦ Creating a Behavior Method Nodes Returns Description setAttribute(attrName, ELEMENT_NODE nothing Sets the specified attrValue) attribute to a specified value removeAttribute(attrName) ELEMENT_NODE nothing Deletes the specified attribute Dreamweaver JavaScript API extensions The Dreamweaver JavaScript API is vast, with more than 600 custom JavaScript functions, enabling the savvy behavior programmer to use JavaScript to accomplish almost any task that the user can perform in Dreamweaver. Although in-depth discussion of the Dreamweaver JavaScript API is beyond the scope of this book, I strongly recommend that behavior pro- grammers take the time to familiarize themselves with what this deep API has to offer. The JavaScript API functions are grouped into the following categories: Assets panel functions Live data functions Behavior functions Menu functions Clipboard functions Path functions Code hints functions Print functions Command functions Quick Tag Editor functions Conversion functions Report functions CSS Styles functions Results window functions Data source functions Selection functions Enablers Server behavior functions External application functions Server model functions File manipulation functions Site functions Find/Replace functions Snippet panel functions Frame and frameset functions Source view functions General editing functions String manipulation functions Global document functions Table editing functions History functions Tag Editor and tag library functions HTML style functions Tag Inspector functions JavaScript debugger functions Timeline functions Keyboard functions Toggle functions Layer and image map functions Toolbar functions Layout environment functions Translation functions Library and template functions Window functions 543504 ch34.qxd 12/10/03 10:43 PM Page 1067 1068 Part VII ✦ Extending Dreamweaver Behavior programmers may find the API functions under Behavior, File Manipulation, Global Document, Path, Selection, and String Manipulation to be of particular interest. The Dreamweaver engineers didn’t stop with the aforementioned JavaScript APIs; they cre- ated additional APIs for file input/output, source control integration, JavaBean management, design notes, Fireworks integration, Flash objects, and more. Extending Dreamweaver has basic documentation about them all. To make the behavior programmer’s life a little easier, I’ve included coverage of some of the most often used API functions. Although the following sections are in no way exhaustive, they do give a good example of how API functions work in Dreamweaver in general and in behav- iors in particular. The Dreamweaver API functions have a prefix of dreamweaver, dom, or site. The dreamweaver prefix can also be abbreviated as dw as in dw.getDocumentDOM(). The dom functions refer to the DOM of a document returned by the getDocumentDOM() function (as explained in the following section). The site functions refer to selections in the Site panel. The dreamweaver.getDocumentDOM() function The getDocumentDOM() function is the starting point for many Dreamweaver JavaScript manipulations. It returns the entire DOM for the specified document, thus enabling the docu- ment to be read and manipulated. Generally, getDocumentDOM() is used in this fashion: var theDom = dreamweaver.getDocumentDOM(“document”); theDom holds the DOM of the current document and, by extension, everything connected to it. Because many behaviors require repeated access to the DOM, it’s good practice to assign it to a global variable (such as theDOM) early on in your script. After you have accessed the document DOM in this manner, you request more specific infor- mation. If, for example, you want to examine the <body> of the current document, you can code it this way: var theDom = dreamweaver.getDocumentDOM(“document”); var theBody = theDom.body; You could also use JavaScript dot notation to shorten the code: var theBody = dreamweaver.getDocumentDOM(“document”).body; The getDocumentDOM() function requires one argument, sourceDoc, which refers to the source document. The argument must be one of the following: ✦ “document”: Sets the reference to the current document. Although the “document” argument can be used from anywhere to read the DOM, any edits applied using it must ultimately be called from within the applyBehavior(), deleteBehavior(), or objectTag() functions — or any function in a command or Property inspector file. ✦ “parent”: Sets the source document to the parent of the current document. This argu- ment is generally used to determine if a document is within a frameset, like this: var frameset = dreamweaver.getDocumentDOM(“parent”); if (frameset) { do code } Tip Note 543504 ch34.qxd 12/10/03 10:43 PM Page 1068 1069 Chapter 34 ✦ Creating a Behavior ✦ “parent.frames[number]” or “parent.frames[‘framename’]”: To access another document in the frameset of which the current document is a member, use one of these two argument forms. The first, “parent.frames[number]”, is usually used when the names of the current frames are unknown or to cycle through any number of frames. The second, “parent.frames[‘framename’]”, is applied in specific cases where the names of the other frames are known and modifications are made to those frames only. ✦ URL: Occasionally, the behavior builder references existing documents, either locally or on the Web. Using a URL—either absolute or relative — as an argument enables you to retrieve information on almost any document you can specify. When using a relative URL, such as this one from Dreamweaver’s Untitled Documents.js file, the URL is rela- tive to the location of the behavior or other extensibility file: var curDOM = dw.getDocumentDOM(‘ / /Templates/Default.html’); Whenever API functions require the DOM object, such as the dom.getSelection() func- tion and others discussed in the following sections, you must first get the DOM of the current document. In all the examples that follow, the variable theDOM is understood to have been established early on, like this: var theDOM = dreamweaver.getDocumentDOM(“document”); The dom.getSelection() function How a behavior performs is quite often dictated by what tag the user selects prior to attach- ing the behavior. The getSelection() function is the first step toward getting all the informa- tion necessary to control the behavior based on a user selection. I emphasize first step because this function returns the selection in the form of byte offsets in memory. A byte offset is a number that points to a memory address. In the case of the getSelection() function, the two byte offsets that are returned mark the beginning and end of the selection in memory. For example, you open a new page in Dreamweaver, type in a phrase such as The Key Points, and then select the first word, The. If you used the getSelection function like this: var selArray = theDOM.getSelection(); alert(selArray); the alert box would return 161,164, which denotes the beginning byte (161) and the ending byte ( 164) offset of the selected word, The. If your beginning and ending byte offsets are the same (as in 164,164), nothing is selected. This fact comes in handy when you want to make sure that the user has selected something before proceeding. To examine what is contained within the byte offsets returned by the getSelection() function, you use the offsetsToNode() function, explained later in this section. The dom.setSelection() function Just as getSelection() retrieves the memory offsets of the current selection, the setSelection() function sets a new pair of memory offsets and thus a new selection. The setSelection() function takes two arguments: offsetBegin and offsetEnd. setSelection() is most often used to restore a user’s selection after various document manipulations have taken place. In this example, the selection is first stored in a variable via getSelection() and then, after much document modification, restored by setSelection: var currSelection = theDOM.getSelection(); // document altering code goes here theDom.setSelection(currSelection[0],currSelection[1]); Note 543504 ch34.qxd 12/10/03 10:43 PM Page 1069 1070 Part VII ✦ Extending Dreamweaver If the new setting does not conform to a valid HTML selection, such as the attributes within a tag, the selection expands to include the entire tag. You can also use setSelection to deselect anything on the page after completing a behavior. All that’s required is that the two arguments be equal. Using the preceding example, the fol- lowing code: theDOM.setSelection(currSelection[1],currSelection[1]); places the cursor after the previous selection, whereas theDOM.setSelection(currSelection[0],currSelection[0]); places it before the selection. The dom.offsetsToNode() function The offsetsToNode() function serves as a translator, converting the byte memory offsets retrieved by getSelection() into readable data. For this reason, you often see the following code combination: selArr = theDOM.getSelection(); selObj = theDOM.offsetsToNode(selArr[0],selArr[1]); where getSelection() returns the array of the selection and the object referenced by that array. As indicated, offsetsToNode() takes two arguments: offsetBegin and offsetEnd, usually expressed as the initial ( 0) and next (1) array elements. After you’ve used offsetsToNode to get the selected object, you can examine or manipulate it. For example, in the custom Replicator command (included on the CD-ROM that accompa- nies this book), I used offsetsToNode to see if the selection made is appropriate (text only) and, if it is not, I call a help function: var offsets = theDOM.getSelection(); var selObj = theDOM.offsetsToNode(offsets[0],offsets[1]); if (selObj.nodeType != Node.TEXT_NODE) { helpMe2(); } The dom.nodeToOffsets() function As the name indicates, nodeToOffsets() is the inverse of offsetsToNode(). Instead of converting memory offsets to an object, nodeToOffsets takes an object reference and returns its memory offsets. This is useful when you manipulate a substring of the selection, usually text. For example, in the custom command Change Case (included on the CD-ROM that comes with this book), after the selected object is retrieved via getSelection and offsetsToNode, nodeToOffsets expresses it in an array that can be uppercased or lowercased at the click of a button. Here’s a fragment of the code from the custom upperCase() function: var theDom = dreamweaver.getDocumentDOM(“document”); var offsets = theDom.getSelection(); var theNode = theDom.offsetsToNode(offsets[0],offsets[1]); if (theNode.nodeType == Node.TEXT_NODE) { var nodeOffsets = theDom.nodeToOffsets(theNode); Note 543504 ch34.qxd 12/10/03 10:43 PM Page 1070 1071 Chapter 34 ✦ Creating a Behavior offsets[0] = offsets[0] - nodeOffsets[0]; offsets[1] = offsets[1] - nodeOffsets[0]; var nodeText = theNode.data; theNode.data = nodeText.substring(0,offsets[0]) + nodeText.substring(offsets[0], offsets[1]).toUpperCase() + nodeText.substring(offsets[1], nodeText.length); } Because nodeToOffsets returns two memory offsets, you can use these as the arguments in setSelection to choose an object on the page. If, for instance, you wanted to select the first link on the page, you use the code as follows: var theDom = dreamweaver.getDocumentDOM(“document”); var theLink = theDom.links[0]; var offsets = theDom.nodeToOffsets(theLink); theDom.setSelection(offsets[0],offsets[1]);The dreamweaver.getTokens() function The getTokens() function is often used in the inspectBehavior() function because it does such a good job of parsing a string. A token is a group of text characters that does not contain any of the specified separators. Generally, the separators in a function are the parentheses that surround the arguments and the commas that separate them. The getTokens() function takes two arguments — the string to be parsed and the separators — and puts the results in an array. For example, note the following string: doGroovoid(‘false’,’Fanfare-Arrival’); To extract the two arguments from this statement, use the getTokens() function as follows: getTokens(“doGroovoid(‘false’,’Fanfare-Arrival’)”,”’(),”); If you set this function equal to an array called argArray, you get the following results: argArray[0] = ‘doGroovoid’; argArray[1] = ‘false’; argArray[2] = ‘Fanfare-Arrival’; Usually the first element of the array, the function name, is ignored. The dreamweaver.getElementRef() function The getElementRef() function is used to gather browser-specific references to a particular object and place them into an array. The getElementRef() function takes two arguments: The first argument is either NS 4.0 or IE 4.0, which reference the Netscape and Internet Explorer formats, respectively; and the second argument is the tag being examined. The string returned puts the specified tag in the format of the named browser. If, for example, getElementRef() is used to get the object reference to a specific layer in Netscape terms, like var theObjNS = dreamweaver.getElementRef(“NS 4.0”, tagArr[i]); the variable, theObjNS, is set to something like document.layers[‘newLayer’]; 543504 ch34.qxd 12/10/03 10:43 PM Page 1071 1072 Part VII ✦ Extending Dreamweaver On the other hand, the same layer, in Internet Explorer terms, like this var theObjIE = dreamweaver.getElementRef(“IE 4.0”, tagArr[i]); returns a string like document.all.newLayer1. Both getElementRef() and getObjectRefs() return browser-correct references for both browsers for the following tags: <a>, <area>, <applet>, <embed>, <select>, <option>, <textarea>, <object>, and <img>. Additionally, references for the tags <div>, <span>, and <input> are returned correctly for Internet Explorer, as <layer> and <ilayer> are for Netscape. Absolutely positioned <div> and <span> tags are also returned correctly for Netscape, but others return the message “cannot reference <tag>”. Naming objects and layers is often critical in JavaScript, as it certainly is with getElementRef() and getObjectRefs(). Dreamweaver can’t return references for unnamed objects; instead, it gives you an “unnamed <tag>” message. Furthermore, Dreamweaver can’t handle refer- ences to a named object if it is in an unnamed layer or form. To help with the naming task, Dreamweaver automatically assigns a name attribute to forms and an ID attribute to layers as they are created. The dreamweaver.getBehaviorTag() function The getBehaviorTag() function returns the tag selected to implement the current behavior. The getBehaviorTag() function can also be incorporated into the behavior setup code to steer the user in the appropriate direction. The getBehaviorTag() function returns the entire tag — name, attributes, values, and any text selected — exactly as it is written (capitalization, spaces, and so on). In most situations, you need only the relevant portion of the tag, its name ( img), for example. You can find the relevant portion of a tag by using JavaScript’s indexOf() method to search a string (the entire tag) for a specified substring. The following code looks to see if the tag selected for the behavior is an <img> tag. If it’s not, the code alerts users to what’s required: function initializeUI() { // uppercase the tag to make indexOf() searching easier var theTag = dreamweaver.getBehaviorTag().toUpperCase(); if (theTag.indexOf(‘IMG’) != -1)) { // Behavior UI initialization goes here } else { alert(“This behavior requires you select an IMAGE to proceed.”); } } Using the initializeUI() function to block access to a behavior is different from using the canAcceptBehavior() function to block access. With the getBehaviorTag() tech- nique, the user is informed of the problem, rather than simply denied access. The dreamweaver.getBehaviorElement() function Another method to discover which tag is selected for the invoked behavior is the getBehaviorElement() function. The major difference between this function and the getBehaviorTag() function is that the former returns the DOM reference to the tag, whereas Note Caution 543504 ch34.qxd 12/10/03 10:43 PM Page 1072 [...]... together to programmatically display Dreamweaver s InsertMenu.htm file: function displayMenu() { var menuPath = dreamweaver. getConfigurationPath() + “/Objects/InsertMenu.htm”; dreamweaver. browseDocument(menuPath); } 107 5 107 6 Part VII ✦ Extending Dreamweaver The dreamweaver. openDocument() and dreamweaver. createDocument() functions The openDocument() and createDocument() functions provide similar capabilities... requires only one argument: the name of the command file Any file named must be located in the Dreamweaver MX 2004\ Configuration\Commands folder The runCommand() function does not return a value but simply executes the specified command The dreamweaver. latin1ToNative() and dreamweaver. nativeToLatin1() functions Dreamweaver provides two functions to help with the localization of your behaviors around the... of an HTML page ✦ You can use Dreamweaver s built-in JavaScript extensions and API functions to build your own actions ✦ Dreamweaver s JavaScript extensions enable you to open existing documents, as well as create and save new ones ✦ Many useful functions can be found in the Dreamweaver MX 2004\ Configuration\ Shared\Common\Scripts folder In the next chapter, you learn how Dreamweaver s server behaviors... alert() method or the Dreamweaver JavaScript extension, browseDocument() To display a brief message, use the alert() method, as in the following code: function displayHelp() { alert(“This behavior works only with rmf files.”); } 108 1 108 2 Part VII ✦ Extending Dreamweaver When you need to bring up a much longer file, use the browseDocument() function: function displayHelp() { dreamweaver. browseDocument(“http://www.idest.com /dreamweaver/ ”);... Altering applied server behaviors Working with Dreamweaver s server behaviors Adding new server behaviors Crafting custom server behaviors ✦ ✦ ✦ ✦ 108 8 Part VII ✦ Extending Dreamweaver tag Dreamweaver automatically places the code in the proper place — and code placement is very important on the server side — when any of its standard server behaviors are used Dreamweaver includes over 25 standard server... two arguments: the name of the action file and the general function call of the action The action chosen must be located in the Dreamweaver MX 2004\ Configuration\Behaviors\Actions subfolder For example, code to call the Play Sound behavior might look like this: var goPS = dreamweaver. popupAction(“Play Sound.htm”,”MM_controlSound(,,)”); Tip To call an action in a subfolder of the Actions folder, specify... Functions As with most other object-oriented programming languages, it’s good programming practice to build a function once and recall it when needed Dreamweaver includes a large library of such useful functions, which are maintained in the Dreamweaver MX 2004\ Configuration\ Shared\MM\Scripts\CMN folder The functions are grouped by category into JavaScript files; currently 18 such files exist, including... document.layers[‘onLayer’].imgOne Dreamweaver Behavior Techniques Creating a behavior is often far more than just stringing together a number of predefined functions Specific techniques exist for many special needs, and if you don’t know them, you can spend many hours redeveloping the wheel In this section, you learn several methods that can help you streamline your work 108 3 108 4 Part VII ✦ Extending Dreamweaver Specifying... use the latin1ToNative() 107 7 107 8 Part VII ✦ Extending Dreamweaver function The argument, a text string, should be already translated into the other language To convert a text string from the user’s encoding system to Latin 1, use the inverse function, nativeToLatin1() Note Neither of these functions has an effect in Windows systems, which are already based on Latin 1 The dreamweaver. relativeToAbsoluteURL()... this function in some of the standard behaviors However, Macromedia recommends that it be used only when the behavior’s dialog box must be larger than 640 × 480 107 9 108 0 Part VII ✦ Extending Dreamweaver The deleteBehavior() function Normally, Dreamweaver automatically handles removal of a behavior’s event handler and associated JavaScript when the user chooses the Remove (–) button in the Behaviors . + “/Objects/InsertMenu.htm”; dreamweaver. browseDocument(menuPath); } Note 543504 ch34.qxd 12 /10/ 03 10: 43 PM Page 107 5 107 6 Part VII ✦ Extending Dreamweaver The dreamweaver. openDocument() and dreamweaver. createDocument() functions The openDocument(). rolloverCmdURL = dreamweaver. getConfigurationPath() + “/Commands/Rollover.htm”; var rolloverDoc = dreamweaver. getDocumentDOM( rolloverCmdURL ); 543504 ch34.qxd 12 /10/ 03 10: 43 PM Page 107 4 107 5 Chapter. be larger than 640 × 480. 543504 ch34.qxd 12 /10/ 03 10: 43 PM Page 107 9 108 0 Part VII ✦ Extending Dreamweaver The deleteBehavior() function Normally, Dreamweaver automatically handles removal of

Ngày đăng: 14/08/2014, 02:20