Adobe Extending Dreamweaver CS4 User Manual
Page 140
134
EXTENDING DREAMWEAVER CS4
Commands
Determine whether the command should be enabled or dimmed
The first task in creating a command is to determine when the item should be active and when it should be dimmed.
When a user clicks the Commands menu, Dreamweaver calls the
canAcceptCommand()
function for each menu item
to determine whether it should be enabled. If
canAcceptCommand()
returns the value
true
, Dreamweaver displays
the menu item text as active or enabled. If
canAcceptCommand()
returns the value
false
, Dreamweaver dims the
menu item. In this example, the menu item is active when the user has selected text in the document.
1
Create a new blank file.
2
Add the following code:
function canAcceptCommand(){
var theDOM = dw.getDocumentDOM(); // Get the DOM of the current document
var theSel = theDOM.getSelection(); // Get start and end of selection
var theSelNode = theDOM.getSelectedNode(); // Get the selected node
var theChildren = theSelNode.childNodes; // Get children of selected node
return (theSel[0] != theSel[1] && (theSelNode.nodeType == Node.TEXT_NODE¬
|| theSelNode.hasChildNodes() && (theChildren[0].nodeType == ¬
Node.TEXT_NODE)));
}
3
Save the file as Change Case.js in the Configuration/Commands folder.
The first lines of the
canAcceptCommand()
function retrieve the selected text by retrieving the DOM for the user’s
document and calling the
getSelection()
function on the document object. Next, the function retrieves the node
that contains the selected text, followed by any children of the node, as shown in the following code. Then, the last line
checks to see if the selection or its first child is text and returns the result as a value of
true
or
false
.
The first part of the
return
statement (
theSel[0] != theSel[1]
) checks if the user has selected anything in the
document. The variable
theSel
is a two-slot array that holds the beginning and ending offsets of the selection within
the document. If the two values are not equal, content has been selected. If the values in the two slots are equal, there
is only an insertion point and nothing has been selected.
The next part of the
return
statement (
&& (theSelNode.nodeType == Node.TEXT_NODE
) checks to see if the
selected node type is text. If so, the
canAcceptCommand()
function returns the value
true
. If the node type is not text,
the test continues to see if the node has children (
|| theSelNode.hasChildNodes()
) and if the type of the first child
node is text (
&&
(
theChildren[0].nodeType == Node.TEXT_NODE))
). If both conditions are true,
canAcceptCommand()
returns the value
true
, and Dreamweaver enables the menu item at the bottom of the
Commands menu, as shown in the following figure: