Category Archives: MarkUp

SGML, (X)HTML, XML and other markup languages.

XBL Part 2: Event Handlers

This is part 2 in my 5 part series on XML Binding Language. If you haven’t already read part 1, I suggest you do so now before you continue reading. XBL provides a mechanism for attaching event listeners to elements, and declaring the conditions under which the handlers should be invoked. In this article, I’m going to compare traditional event handling techniques with those that will be provided using by XBL.

Traditional Event Handling

The following example illustrates some typical unobtrusive scripting techniques to attach event listeners, including both the window.onload property and the addEventListener() function.

window.onload = function() {
    var nav = document.getElementById("nav");
    var li = nav.getElementsByTagName("li");
    for (var i = 0; i < li.length; i++) {
        li[i].addEventListener("mouseover", doSomething, false);
    }
}

Another common method, though generally considered bad practice these days, is to use the HTML onevent attributes, like the following.

<li onmouseover="doSomething();">...</li>

There are advantages and disadvantages to both methods, but the former is generally considered better because it separates the behaviour layer from the markup. However, the latter is a simple declarative syntax that can be quite convenient in some cases.

Handling Events with XBL

In XBL, instead of requiring authors to use a script to search for the elements, the event listeners are attached to those that the binding is attached to. XBL provides a simple declerative syntax which also continues to separate the behaviour layer from the semantic markup layer. Event listeners are declared using both the handlers element and its child handler elements.

In the previous article, we looked at how bindings are associated with elements using a selector, just like in CSS. For example, this binding will be attached to all li elements within an element with id="nav".

<xbl xmlns="http://www.w3.org/ns/xbl">
  <binding element="#nav li">
    <handlers>
      <handler event="mouseover">
        doSomething();
      </handler>
    </handlers>
  </binding>
</xbl>

If present, only one handlers element is allowed within a binding, but it can contain as many child handler elements as required, to capture as many different events as you like. This binding declares a single event handler that listens for the mouseover event. When the mouseover event is fired on a bound element (i.e. an element to which this binding is attached), the handler is invoked in effectively the same way it would have been using the other methods shown above.

Event Filters

There are often times when you only want to handle an event under certain conditions. For example, when you want to capture a click event and do something only when the user clicks the left mouse button; or capture a keyboard event and perform different functions depending on which key was pressed. In traditional scripting techniques, you have to check the values of certain properties using if or switch statements in your function, like the following.

function doSomething(e) {
    var code;
    e = e || window.event;
    code = e.keyCode || e.which;
    switch(code) {
        ...
    }
}

Much of that involves handling of browser incompatibilities, but even if all browsers supported the DOM Events standard, it’s still quite complicated. XBL addresses this by providing a simple declarative syntax for describing these conditions using attributes on the handler element.

In the following example, separate handlers are provided for for handling the keypress events depending on which character was entered. The first handles the character a, the second handles b. If any other character was entered, neither of these two handlers will be invoked.

<handlers>
  <handler event="keypress" text="a">
    doSomethingA();
  </handler>
  <handler event="keypress" text="b">
    doSomethingB();
  </handler>
</handlers>

Similarly, in the following example, the handler will only be invoked when the user left clicks while holding the Shift key down.

<handlers>
  <handler event="click" button="0" modifiers="shift">
    doSomething();
  </handler>
</handlers>

Other Common Event Filters

There are several other filters that can be used. The following list is a subset of the available attributes for this purpose. I suspect these will be the most commonly used filters because they cover the majority of mouse and keyboard event usage on the web today.

button
A space separated list of mouse buttons pressed by the user. e.g. button="0 2" matches either the left or right mouse buttons.
click-count
The number of times the user clicked. e.g. click-count="2" matches double clicks.
text
The text entered by the user. This is different from the key code because it matches the letter that was entered, regardless of the keys that were pressed. This is particularly important for languages that require several key presses to enter certain letters.
modifiers
Modifer keys, including alt, control, shift, meta, etc.
key
Matches against the keyIdentifier value defined in DOM 3 Events
key-location
For matching the location of the key that was pressed on the keyboard, including standard, left, right and numpad.

In the next article in this series, I’ll be taking a look at XBL Templates, which will provide significant presentaional enhancements, particularly in regards to layout.

XBL Part 1: Bindings

XML Binding Language (XBL) is a mechanism for extending the presentation and behaviour of a document. The XBL 2.0 specification recently reached Last Call and it has some very cool features to look forward to using in a few years. It’s somewhat based upon the original XBL 1.0 specification created and implemented by Mozilla, though it has been significantly redesigned and is not backwards compatible with it.

While reading this, keep in mind that XBL is still a working draft and any feature I discuss may change significanly between now and when it becomes a recommendation. Presently, there are no implementations of XBL 2.0, so you can’t use it yet.

Bindings

A binding is a way to attach presentation and behaviour to an element. The concept is similar to the way we already style elements using CSS and attach event listeners to them with JavaScript, but the idea is to add an extra layer of abstraction in between to simplify the process. Bindings are a not a way to replace existing authoring tools like CSS and JavaScript, but rather an enhancement to them.

There are four main aspects of a binding: implementations, templates, handlers and resources. In this whopping 5 part series, I intend to give you a brief overview of each of these components to explain their purpose and functionality.

Implementations
Describe a set of methods, properties and fields on an element.
Handlers
These offer an improved way to declare event listeners.
Templates
A way to enhance the presentation (particularly layout) beyond what is possible with existing CSS techniques.
Resources
Additional stylesheets, images, video, audio or any other content associated with the binding.

Sample Bindings

Bindings can be attached to elements in several ways: a selector in the element attribute of the binding element, the ‘binding‘ property in CSS or using a script.

The element Attribute

The element attribute specifies a selector. The same type of selector you use with CSS, so it’s very easy to understand. This binding will be attached to all elements that match the selector: #nav li.

<xbl xmlns="http://www.w3.org/ns/xbl">
  <binding element="#nav li">
    <implementation>...</implementation>
    <template>...</template>
    <handlers>...</handlers>
    <resources>...</resources>
  </binding>
</xbl>

The ‘binding‘ Property

The ‘binding‘ property can be used in in your CSS to attach a binding, in exactly the same way you apply any other other style to an element.

bindings.xml:

<xbl xmlns="http://www.w3.org/ns/xbl">
  <binding id="foo">
    <implementation>...</implementation>
    <template>...</template>
    <handlers>...</handlers>
    <resources>...</resources>
  </binding>
</xbl>

The stylesheet:

#nav li { binding: url(bindings.xml#foo); }

Using a Script

Elements will implement the ElementXBL interface, which defines three methods: addBinding(), removeBinding() and hasBinding(). The addBinding() method can be used to attach a binding to an individual element using a script, like this:

var e = ...; // Get the element somehow
e.addBinding("bindings.xml#foo");

XML Prologue

One thing I come across frequently is incorrect terminology. I’ve written about this topic once before (see HTML Tags) and others have discussed similar topics as well, particularly relating to elements, attributes and tags. But a more specific area that deserves a little more attention is the distinction between the DOCTYPE, the XML declaration and the XML prolog and other things within it.

The XML Prolog is the section at the beginning of an XML document which includes everything that appears before the document’s root element. The XML declaration, the DOCTYPE and any processing instructions or comments may all be a part of it. The following figure illustrates this concept.

The diagram highlights the XML Prolog at the beginning of a sample XHTML 1.0 document containing the XML declaration, a processing instruction, a comment and the DOCTYPE.

In fact, the XML Prolog is always present in every XML document, though it may in fact be empty because all of those are optional in some circumstances.

The XML Declaration

<?xml version="1.0" encoding="UTF-8"?>

The XML declaration, if present, must occur at the very beginning of the file. It may not be preceded by anything except for a possible Byte Order Mark (depending on the character encoding). It is mostly used to provide XML version information and to declare the character encoding of the document. There is another thing called the standalone document declaration; but since it’s rarely needed or used and its purpose is not easy to explain, just ignore it.

Presently, only XML 1.0 and XML 1.1 are defined. Either may be used, but the decision should not be made lightly. Do not just use version="1.1" because it is higher version number. For most authors these days, version="1.0" should be used. In fact, unless you have a specific reason that requires the use of XML 1.1 features, you should stick with 1.0.

The encoding declaration, if present, must declare the encoding of the document. Authors may use any encoding supported by user agents, but are encouraged to use charsets registered with IANA (preferably UTF-8 or UTF-16). If the declaration is not present, the document must be encoded as UTF-8 or UTF-16 (unless it specified by a higher level protocol, like HTTP).

Processing Instructions

<?xml-stylesheet type="text/css" href="/style/design"?>

Processing Instructions are used to provide instructions to applications processing the document. The example of the xml-stylesheet PI given in the above diagram is used to instruct an application to apply a stylesheet to the document.

PIs can be used almost anywhere within the document. Though, only those that appear prior to the root element are considered part of the prolog.

Comments

<!-- This is a comment -->

Most people know what comments are, there’s not much I need to say about them. However, like PIs, they’re only considered part of the prolog if they appear before the root element.

The Document Type Declaration

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Many authors will have seen and used a DOCTYPE in their documents, although there are still many who don’t. The DOCTYPE is used to reference a Document Type Definition and is mostly used for validation purposes.

Many people know that using specific DOCTYPEs will trigger standards mode in browsers, but this does not apply to XML documents. DOCTYPE sniffing only applies to HTML documents (i.e. any document served as text/html). Browsers have, thankfully, not introduced it into XML processing. Henri Sivonen explains more about this in Activating the Right Layout Mode Using the Doctype Declaration.