Back to XUL: JavaScript Logic - Scripting the Menubar: Close, Exit and New
(Page 2 of 4 )
Next we need to add the behavior to our menubar. We’ll go through the menus one at a time and script each menu action. The File menu contains the Open and Save actions, both of which require a lot of effort and the use of XPCOM, so for the time being, we will leave these and come back to them later.
The first action we will script then is the Close action:
function closeFile() {
var editor = document.getElementById('mainContent');
editor.setAttribute('src', 'about:blank');
}
Calling the window.close() method will close the whole application rather than just the currently open page, so we can set the src of the editor element to "about:blank," which will effectively generate a blank page. The call to this function is added to the Close menuitem:
oncommand="closeFile()"
Next, we need to wire up the Exit action. In the JavaScript file add:
function closeApp() {
window.close();
}
Then, to the Exit menuitem element add:
oncommand="closeApp()"
As you can see, this action is extremely simple; because we set the editor type as content-primary, we can treat it as the main window and simply call the window.close method to quit the whole application.
The New menu contains a sub-menu giving the user a choice of new files. We can cheat here to save time and effort by using a series of template files, one for each of the options. To open a new XUL file, we just open (or re-open) the xul.txt file:
function newXul() {
var editor = document.getElementById('mainContent');
editor.setAttribute('src', 'xul.txt');
}
Add the call to this function in the JavaScript file, and don’t forget to add the oncommand event handler:
oncommand="newXul()"
Similarly, the new HTML and new XML document menu actions are done under exactly the same premise:
function newHtm() {
var editor = document.getElementById('mainContent');
editor.setAttribute('src', 'htm.txt');
}
function newXml() {
var editor = document.getElementById('mainContent');
editor.setAttribute('src', 'xml.txt');
}
function newRdf() {
var editor = document.getElementById('mainContent');
editor.setAttribute('src', 'rdf.txt');
}
You should be able to guess how and where to put the event handlers for these. If not, each oncommand goes at the end of the menuitem that calls the required function:
oncommand="newHtm()"
oncommand="newXml()"
oncommand="newRdf()"
The text files used for these functions can just sit in the main content folder alongside the other interface files. This is a great way to set up the new files because it gives you precise control over what appears in the new document, and saves on using lots of document.writeLn() methods to generate the template text.
Next: Scripting the Menubar: Open >>
More XML Articles
More By Dan Wellman