W3C

XBL 2.0 Primer: An Introduction for Developers

W3C Working Draft 18 July 2007

This Version:
http://www.w3.org/TR/2007/WD-xbl-primer-20070720/
Latest Version:
http://www.w3.org/TR/xbl-primer/
Editors:
Lachlan Hunt, (Invited Expert) <lachlan.hunt@lachy.id.au>
Marcos Caceres, (Queensland University of Technology) <m.caceres@qut.edu.au>

Abstract

This practical guide provides you with the knowledge required to effectively use the XML Binding Language 2.0. It introduces both the basic and advanced concepts of XBL and describes its syntax and scenarios that should be considered best-practice. It also describes the purpose of the language elements described in the XBL 2.0 specification.

XBL describes the ability to associate elements in one document with script, event handlers, styles, and more complex content models in another document. You can use XBL to re-order and wrap content so that, for instance, simple HTML or XHTML markup can have complex CSS styles applied without requiring that the markup be polluted with multiple div elements. In addition, if you are a programmer, you can use XBL to implement new DOM interfaces, and, in conjunction with other specifications, it enables arbitrary XML tag sets to be treated as "widgets" (pluggable user interface components).

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 18 July 2007 First Public Working Draft of the XBL 2.0 Primer: An Introduction for Developers. This document is produced by the Web Application Formats (WAF) Working Group (WG). This WG is part of the Rich Web Clients Activity and this activity is within the W3C's Interaction Domain.

Web content and browser developers are encouraged to review this draft. Please send comments to public-appformats@w3.org, the W3C's public email list for issues related to Web Application Formats. Archives of the list are available. The editor's draft of this document is available in W3C CVS. A detailed list of changes is also available from the W3C CVS server.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Please note that at the time of writing there are no implementations of XBL 2.0 publicly available, so everything in this document is untested.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

Table of Contents

1. Chapter 1 - Overview of XBL

The move in Web development towards avoiding the table element for layout has led developers to consider how to exploit other HTML elements, CSS, and JavaScript to achieve complex layouts. To a large extent, this move has been fueled by proponents of the Web 2.0 movement who promote the importance of having highly accessible content that is both adaptive and provides an engaging user experience. However, a new problem has emerged where by Web documents are now heavily ‘polluted’ with the semantically-neutral div element and complex JavaScript and CSS that is hard for authors to maintain.

The XML Binding Language 2.0 (XBL) is a declarative language that can be used together with existing or new Web documents to enhance their presentation, behavior, accessibility, and maintainability. This Primer is designed to provide you with the practical knowledge required to use XBL effectively in your work. It introduces both the basic and advanced concepts of XBL and describes its syntax and best-practices usage scenarios. It also describes the purpose of the language elements described in the XBL specification document.

1.1. Intended audience

The primary intended audience for the Primer is Web developers: that is, anyone who has some experience working with HTML, CSS, JavaScript, and perhaps some exposure to XML. This assumes that the reader is familiar with those, and other related Web development techniques and technologies. A second intended audience are XML developers who are considering XBL as a tool to enhance the behavior and programmatic functionality of DOM elements. Where relevant, we make note of advanced functionality of XBL specifically for XML developers or advanced Web developers.

We have written this document as a series of tutorials for developers who want to learn XBL in a ‘hands-on’ manner. We have made every effort to write this in a relaxed style that should be understandable by a large audience. While this is not a technical specification and it does not include any implementation details or requirements, this may still be a useful introduction to the concepts of XBL for people who are intending to implement the XBL specification.

1.2. How the Primer is structured

Need to revise this section later!!!

XBL is a powerful and sometimes complex language with many features. In order to effectively demonstrate the relevant aspects of the language, we have split the primer into 6 chapters:

Chapter 1 - Overview of XBL
Introduces you to the high level concepts and functionality of XBL. This chapter is useful for getting a holistic view of the language and what its used for.
Chapter 2 - Reordering content
Introduces you to XBL's ability to reorder content. Apart from introducing developers to bindings, this scenario introduces loading and applying custom style sheets.
Chapter 3 - Form controls
Introduces you to how XBL can be used for client-side form validation by creating reusable bindings.
Chapter 4 - XBL and XMLHttpRequest
introduces you to how you can simplify Ajax style development with XBL.
Chapter 5 - Enhancing user experience
shows you how you can take existing content and enhance its presentation and user experience with XBL.
Chapter 6 - Re-purposing content to increase accessibility:
to be written.
Appendix - Language reference:
The appendix has been written so you can quickly find information about each XBL elements and see examples of how they can be used to solve common problems. It also provides relevant link

1.3. Conventions used in this document

Conventions used in this document... any preferred conventions (eg. code conventions? figure styles? any exemplar Web sites?)? please suggest some.

1.4. XBL

XML Binding Language (XBL) 2.0 is a mechanism for extending the presentation and behavior of a document. XBL 2.0 is based upon the original XBL 1.0 specification created and implemented by Mozilla, though it has been significantly redesigned and is not backwards compatible. One of the goals of XBL is to allow you to directly enhance the user experience of Web documents without needing to overuse structuring elements, such as the div element, in your HTML.

XBL provides various mechanisms to dynamically pre-load and include new content and style sheets into a document, and to enhance HTML or XML elements with scripted functionality. For example, an HTML input element can automatically validate user input via a custom script that is bound to it using XBL. These features potentially translate into a richer end-user experience and documents that are easier to code, style, and maintain.

XBL is structured into several different components. The bindings are used to attach presentation and behavior to an element, and the scripts are used to define helper functions used by the bindings. The bindings are comprised of templates, event handlers, API implementations and resources (figure 1).

Figure 1. Structure of an XBL Document

1.5. Bindings

A binding is a way to attach presentation and behavior to an HTML or XML element. The concept is similar to the way we already style elements using CSS and attach event listeners to them with JavaScript, but by adding an extra layer of abstraction in between simplifies the development 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: templates, handlers, implementations and resources.

Templates
A way to enhance the presentation (particularly layout) beyond what is possible with existing CSS techniques.
Handlers
Offer an improved way to declare event listeners (eg. mouse and key events).
Implementations
A means to add new methods and properties to a XML or HTML element.
Resources
Allow you to load style-sheets and prefetch images, video, audio or any other content associated with the binding.

1.6. Attaching Bindings

Bindings can be attached to elements in several ways using:

  1. the 'element' attribute of the binding element via a CSS-style selector [SELECTORS],
  2. the 'binding' property in CSS,
  3. the 'addBinding()' method in a script.

We discuss these three attachment methods below.

1.6.1. The element Attribute

To create a binding using the element attribute of a binding element you need to specify a selector. It’s the same type of selector that is used in 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>

1.6.2. 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="demo">
    <implementation>...</implementation>
    <template>...</template>

    <handlers>...</handlers>
    <resources>...</resources>
  </binding>
</xbl>

The style sheet:

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

1.6.3. Using the addBinding() method

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 = getElementById("example"); // Get the element
e.addBinding("bindings.xml#foo");  // Attach the binding

It is also possible to check if a binding has been attached using the hasBinding() function.

if (e.hasBinding("bindings.xml#foo")) {
   // Do something
}

Bindings can also be detached using the removeBinding() function.


e.removeBinding("bindings.xml#foo");

1.7. Event Handlers

As stated earlier, handlers offer an improved way to declare event listeners (eg. mouse and key events).

1.7.1. 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 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 behavior layer from the markup. However, the latter is a simple declarative syntax that can be quite convenient in some cases.

1.7.2. 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 declarative syntax which also continues to separate the behavior layer from the semantic markup layer. Event listeners are declared using both the handlers element and its child handler elements. 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.

1.7.2.1. 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 incompatibilities between legacy browsers, but even if all browsers supported the DOM Events standard, it is 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>
1.7.2.2. 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. These are expected to 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
Modifier 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.

1.8. Templates

Templates are used to control the presentation of a document. They can be used to reorder and restructure content in the document without affecting the underlying DOM.

Templates are created using the template element within a binding. The templating model allows you to combine elements from the document with additional elements in creative ways, removing the need for unnecessary and extraneous elements to be added to the original document. You could, for example, use XBL to extract the data from an HTML table and present it as a chart using SVG.

An important concept to grasp is that regardless of what content you include in the template, the template does not alter the semantics of the original document. For example, in an HTML document, a heading could be bound to a binding with a template containing an SVG image. The bound element still semantically represents a heading, only its presentation has changed from plain text to an image. That concept shouldn't’t be too hard to grasp, that example (in principle) is not much different from any of the widely used image replacement techniques, it only differs in implementation.

The XBL content element can be used to insert content from the document into the template. The includes attribute value is a selector, used to select which elements to insert into the tree at that location. The div element is provided as a generic structural element that you can use for any purpose you like.

1.8.1. Shadow Trees

When elements are bound, the contents of their binding’s template are cloned and appended to them as children, creating shadow trees. Shadow trees exist outside of the normal DOM and are thus transparent to ordinary DOM processing. In other words, shadow trees are rendered as though they were part of the original document, but do not actually exist within the document itself.

<body>
  <div id="main">...</div>

  <div id="nav">...</div>
</body>

Using XBL, the content can be reordered and restructured, which will allow for more complex styles to be applied.

<xbl xmlns="http://www.w3.org/ns/xbl">

  <binding element="body">
    <template>
      <div id="container">
        <div id="left"><content includes="#nav"/></div>

        <div id="right"><content includes="#main"/></div>
      </div>
    </template>
  </binding>

</xbl>

This will create the following shadow tree.

Need a diagram

1.9. Implementing Interfaces

The implementation element describes a set of methods and properties that are attached to the bound element. That is, a way to enhance the bound element’s DOM interface. For example, if you wanted to add custom validation to a HTMLInputElement, you would need to do the following in JavaScript:

var customInput    = document.createElement("input");
myInput.max_value  = 56; 
myInput.checkValue = function() {
  // Custom validation
};

That example illustrates the basic way in which we can add properties and methods to an already existing HTML element. Exactly the same technique can already be used to add properties and methods to an element, and this is similar to what the implementation element is designed to do. The equivalent to the example above in XBL would be.

<xbl xmlns="http://www.w3.org/ns/xbl">
  <binding element="#customInput">
    <implementation>

    ({
      max_value: 56,
      checkValue: function() {
        // Custom validation
      }
    })
    </implementation>
  </binding>
</xbl>

In the HTML you would have:


<input type="text" id="customInput"/>

In this example, the binding is attached to elements matching the selector: #customInput.

1.10. Resources

Resources include style sheets and additional files that are used by the binding, such as images, audio and video. The style sheets are used to add style to the binding’s template.

This section is incomplete

1.11. Scripts

The XBL script element, which is similar to the script element in HTML, can be used to define helper functions for your bindings.

Just like in HTML, scripts can either be script resources using the script element's src attribute and declare as many script elements as you need:

<xbl xmlns="http://www.w3.org/ns/xbl">
  <script src="example.js"/>

  <script><![CDATA[
    function foo(){
      example(); // Assume this is defined in example.js
      ...
    }
  ]]></script>
  ...
</xbl>

In the following example, the doSomething() function that is defined in an XBL script element will be automatically called when binding foobar is attached to an element.

<xbl xmlns="http://www.w3.org/ns/xbl">
  <script>
    function doSomething(){...};
  </script>
  <binding id="foobar">

    <implementation>
    ({
      xblBindingAttached: function() {
        doSomething();   // Calls the function defined in the script element
      } 
    })
    </implementation>
  </binding>
</xbl>

The default scripting language is JavaScript. Other languages may be used by specifying them with the script-type attribute on the xbl element. Since JavaScript is the most common scripting language on the Web, the default will usually be acceptable to most authors.

Functions and variables defined in the XBL script element are scoped to the XBL document, so they cannot be accessed from the bound document. Conversely, for security reasons, functions defined in the bound document cannot be invoked from within the XBL document. For example, the following will not work:

<html xmlns="http://www.w3.org/1999/xhtml">            
  <xbl xmlns="http://www.w3.org/ns/xbl">
    <script>

      function bar(){...}
      foo();  //error, foo is undefined!
    </script>
  </xbl>
  <!-- script in  the XHTML namespace --> 
  <script  type="text/javascript">
    function foo(){...}
    bar(); //error, bar is undefined!
  </script>

</html>

Chapter 2. Reordering content

To be written...

Chapter 3. Form controls

To be written...

Chapter 4. XBL and XMLHttpRequest

To be written...

Chapter 5. Enhancing user experience

To be written...

Chapter 6. Re-purposing content to increase accessibility:

To be written...

Appendix. Language reference

To be written...

References

This section will be done once the rest is done.

Acknowledgements

The editors would like to thank the following people for their contributions to this specification: