05. The XUL Document Object Model
Using the Document
The Document is a lot of things. At it's most basic, it is the abstract representation of your Xul application. It also serves as the following:
- A Factory for creating new XulComponents
- A Registry for adding and removing bindings and overlays
- A Broker for firing methods on Event Handlers
- A Utility allowing you to generically add threads to the "Event Thread" of whatever UI Toolkit is running
All XulEventHandler instances are given a reference to the XulDomContainer when they're registered. From this you can access the Document for you application. If your event handler extends AbstractXulEventHandler you'll gain automatic access to the Document through a variable called appropriately enough, "document"
The Document as The UI Tree
Most of the time you'll be using the Document to grab references to UI elements of your running application from your Event Handlers. This is done using the following methods of the Document:
Document Method |
Result |
getElementById(String id) |
Element with the given id |
getElementsByTagName(String name) |
List of elements with the same tag name |
getElementsByXPath(String path) |
List of elements matching the given xpath expression |
getElementsByXPath(String path) |
List of elements matching the given xpath expression |
getFirstChild(), getParent(), getChildNodes() |
Methods of Xul Document Elements (And the document itself) |
The Document as a component factory
Creating new UI elements through the document keeps code agnostic from the actual toolkit in use. The syntax is similar to standard XUL/Javascript. The following example adds a button to a panel.
XulVbox panel = (XulVbox) document.getElementById("targetPanel"); XulButton newButton = (XulButton) document.createElement("button"); newButton.setLabel("Test"); newButton.setOnclick("handler.doSomething()"); panel.addChild(newButton);
The Document as The Binding Context
You'll most likely be using a BindingFactory for your bindings which already handles adding bindings to the Binding Context (covered later). You may still have need to add and remove a binding directly, especially when implementing Xul Tags. The document allows for this
Binding bind = new DefaultBinding(sourceObj, "sourceProperty", targetObj, "targetProperty"); document.addBinding(bind); // sometime later document.removeBinding(bind);
The Document Helps With Overlays
Overlays are an advanced topic covered here (link). You can use the Document to add and remove them at runtime as needed.
document.addOverlay("overlay.xul"); document.removeOverlay("overlay.xul");
The Document Helps with Event Threads
Often you'll need to run something that may take a little while. You may be saving a file over a network for instance. While it's processing you don't want to hang the UI. To get around this problem create a new Runnable instance and pass it to the Document!
document.invokeLater(new Runnable(){ public void run() { //do something long } });