Abstract
This specification describes the ability to map elements to script,
event handlers, CSS, and more complex content models. This can be used 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 semantically neutral div elements.
It can also be used to implement new DOM interfaces, and, in conjunction with other specifications, enables arbitrary tag sets to be implemented as widgets. For example, XBL could in theory be used to implement XForms.
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 7 September 2006 Last Call Working Draft of XBL 2.0. If you wish to make comments regarding this document, please send them to public-appformats@w3.org (subscribe, archives) using the marker "[XBL]" in the subject of the email so that it will be tracked as an official W3C Last Call comment. The deadline for Last Call comments is 7 December 2006. An alternate email list for XBL discussion is dev-tech-xbl@mozilla.org (subscribe, archives), but the W3C will not be officially tracking comments on that list. All feedback is welcome.
Implementers should be aware that this specification is not stable. Implementers who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation stage should join the aforementioned mailing lists and take part in the discussions.
The editor's copy of this specification is available in W3C CVS. A detailed list of changes is available from the CVS server.
This specification is a (non-backwards-compatible) revision of Mozilla's XBL 1.0 language, originally developed at Netscape in 2000, and originally implemented in the Gecko rendering engine. [XBL10]
This specification was developed by the Mozilla Foundation and its contributors, in conjunction with individuals from Opera Software ASA, Google, Inc, and Apple Computer, Inc, to address problems found in the original language and to allow for implementations in a broader range of Web browsers.
This document is also based, in part, on work done in the W3C's Bindings Task Force. However, no text from that collaboration, other than that written by the aforementioned contributors, remains in this specification. Inspiration was similarly taken from other efforts, such as HTML Components. [HTC]
Although they have had related histories, this specification is separate from the W3C's "sXBL" drafts, and is not compatible with them. (The two efforts use different namespaces, for one.)
While the body of this specification was created outside the W3C, the W3C Web Application Formats Working Group is now guiding this specification along the W3C Recommendation track.
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.
Table of Contents
- 1. Introduction
- 2. XBL
Elements
- 2.1. The xbl Element
- 2.2. The binding Element
- 2.3. The implementation Element
- 2.4. The template Element
- 2.5. The content Element
- 2.6. The inherited Element
- 2.7. The xbl:inherits Attribute
- 2.8. The xbl:pseudo Attribute
- 2.9. The div Element
- 2.10. The handlers Element
- 2.11. The handler Element
- 2.12. The resources Element
- 2.13. The style Element
- 2.14. The prefetch Element
- 2.15. The script Element
- 2.16. The id Attribute of XBL Elements
- 3. Resources
- 4. Binding Attachment and Detachment
- 4.1. The Bindings-Are-Ready State
- 4.2. Attachment using
<binding element=""> - 4.3. Attachment using CSS
- 4.4. Attachment using the DOM
- 4.5. Binding Attachment Model
- 4.6. Handling Insertion and Removal from the Document
- 4.7. Binding Inheritance
- 4.8. Views and Attachment
- 4.9. Attachment During Document Load
- 4.10. Binding Detachment Model
- 5. Shadow Content
- 5.1. Rules for Shadow Content Generation
- 5.2. Rules for Shadow Content Destruction
- 5.3. Attribute Forwarding
- 5.4. Processing
contentElements - 5.5. The Final Flattened Tree
- 5.6. Handling DOM Changes
- 5.7. Shadow Content and CSS
- 5.8. Shadow Content
and
xml:base - 5.9. Shadow Content and Other Things
- 5.10. Binding Style Sheets
- 6. Binding Implementations
- 7. Event Handlers
- 7.1. Event Forwarding
- 7.2. Registering Event Handlers with the
handlerElement - 7.3. Mouse Event Handler Filters
- 7.4. Key Event Handler Filters
- 7.5. Text Input Event Handler Filters
- 7.6. Mutation Event Handler Filters
- 7.7. Modifiers
- 7.8. Event Flow and Targeting Across Shadow Scopes
- 7.9. The Default Phase
- 7.10. Focus, DOMFocusIn, Blur, and DOMFocusOut Events
- 7.11. Mouseover and Mouseout Events
- 7.12. Event Handlers Implemented in ECMAScript
- 8. DOM Interfaces
- Acknowledgments
- References
1. Introduction
This specification defines the XML Binding Language and some supporting DOM interfaces and CSS features. XBL is a mechanism for overriding the standard presentation and interactive behavior of particular elements by attaching those elements to appropriate definitions, called bindings. Bindings can be attached to elements using either cascading style sheets, the document object model, or by declaring, in XBL, that a particular element in a particular namespace is implemented by a particular binding. The element that the binding is attached to, called the bound element, acquires the new behavior and presentation specified by the binding.
Bindings can contain event handlers that watch for events on the bound element, an implementation of new methods, properties and fields that become accessible from the bound element, shadow content that is inserted underneath the bound element, and associated resources such as scoped style sheets and precached images, sounds, or videos.
XBL cannot be used to give a document new semantics. The meaning of a document is not changed by any bindings that are associated with it, only its presentation and interactive behavior.
To help readers understand how certain features can be used, this specification includes some examples.
In these examples, a long ellipsis ("...") is used to indicate elided content that would be present in a full example but has been removed for clarity.
Here we see a simple binding being used to reorder content in an HTML
page, so that the element with class="nav" is positioned
before the element with class="main". CSS associated with
the binding is then used to position the two elements.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="nav-then-main">
<template>
<div id="wrapper">
<div id="col2"><content includes=".nav"/></div>
<div id="col1"><content includes=".main"/></div>
</div>
</template>
<resources>
<style>
#wrapper { display: table-row; }
#col1, #col2 { display: table-cell; }
</style>
</resources>
</binding>
</xbl>
The HTML page associated with such a binding might look like:
<!DOCTYPE HTML> <html> <head> <title>Demo</title> <link rel="stylesheet" href="example.css"> </head> <body> <div class="main"> <h1>Demo</h1> ... </div> <div class="nav"> <p><a href="http://example.com/">Home</a></p> ... </div> </body> </html>
The CSS stylesheet referred to from that document would include
various stylistic rules, and would in particular contain a link to the
XBL file, making it apply to the body element so as to
reorder the two child elements:
/* colors and Fonts */
h1 { font: 2em sans-serif; color: green; background: white; }
...
/* Reorder content */
body { -xbl-binding: url(example.xbl#nav-then-main); }
The result of all the above is equivalent to the result one would get
if one simply placed the div element with
class="nav" before the div element
with class="main". However, the effect is achieved without
needing any changes to the markup. This allows the same markup to be
given different presentations dynamically. It also allows changes to be
applied across entire sites by merely changing global stylesheet and
binding files, much as CSS can be used to change the layout and
presentation of a site even without XBL.
Since the examples are all untested (there are no XBL2 implementations at the time of writing), it is quite possible that they have errors. Please report any errors you think you see, so that we can correct the examples.
1.1. Terminology and Conventions
A binding is the definition of behavior that can be applied to an element so as to augment its presentation.
An XBL subtree is a subtree in an XML
document (an XML instance), the subtree having as its root
node an xbl element in the XBL namespace, which is used
to define bindings. XBL subtrees can stand alone in XBL documents, or can be
included in non-XBL
documents.
In the following XHTML example, the XBL subtree is the portion of the markup that is emphasized.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
<xbl xmlns="http://www.w3.org/ns/xbl">
<script><[CDATA[
function fmt(n) {
if (n < 10)
return "0" + n;
else
return n;
}
]]></script>
<binding element=".date">
<implementation>
({
xblBindingAttached: function() {
var tm = /(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d) UTC$/.exec(this.boundElement.textContent);
var date = new Date();
date.setUTCFullYear(parseInt(tm[1], 10));
date.setUTCMonth(parseInt(tm[2], 10) - 1);
date.setUTCDate(parseInt(tm[3], 10));
date.setUTCHours(parseInt(tm[4], 10));
date.setUTCMinutes(parseInt(tm[5], 10));
date.setUTCSeconds(0);
this.boundElement.textContent = date.getFullYear() + "-" +
fmt(date.getMonth() + 1) + "-" +
fmt(date.getDate()) + " " +
fmt(date.getHours()) + ":" +
fmt(date.getMinutes()) + " LT";
this.boundElement.title = "Adjusted to local time zone"
},
})
</implementation>
</binding>
</xbl>
</head>
<body>
<h1>Demo</h1>
<p class="date">2006-08-10 18:40 UTC</p>
<p>...</p>
</body>
</html>
(As an aside, the binding defined in this example causes elements with
class="date" to have their content parsed into a UTC date
and converted into a local time. The binding mutates the original DOM to
do this, and it doesn't reflect any dynamic changes made to the
element's content; there are better, albeit slightly more involved, ways
of achieving the same effect that don't have these problems.)
An XBL document is an XML document that
has the xbl element at its root.
A non-XBL document is an XML document that contains elements from multiple namespaces, with its root element being from a namespace other than XBL (e.g. XHTML).
The example above is an example of a non-XBL document that contains an XBL subtree.
The term binding document is used to mean either an XBL document or a non-XBL document containing one or more XBL subtrees.
A bound element is an XML or HTML element to which a binding has been applied.
In the example above, the
first p element is the bound
element.
A bound document is an XML or HTML document containing one or more bound elements.
In the example at the top of this section, the document is both the binding document (because it contains the definition of the binding), and the bound document (because it contains the affected bound element). In the example in the introduction section, the HTML file is the bound document, and the XBL file is the binding document.
A shadow tree is a tree of nodes created by
cloning a binding's shadow content
template. A bound element can have zero, one, or more shadow
trees. If a bound element has any, they are combined by the user agent,
along with the element's explicit
children, to form the final flattened
tree. Shadow trees are hidden from normal DOM processing
(hence the name "shadow"); they are not accessible via Core DOM
navigation facilities such as firstChild or
nextSibling. (See: shadow
content.)
The term shadow content refers to the various nodes in the shadow tree(s) of a bound element. Shadow content is created by cloning shadow content templates during binding attachment. (See: shadow content.)
In the following sample binding, the shadow
content template is emphasized. (This example is an
inaccessible implementation of the proposed HTML5 details disclosure element: it opens and closes when
clicked, and reflects its current state in the element's
"open" attribute.)
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding element="details">
<template>
<div state="hidden" id="container">
<div id="header"><content includes="legend:first-child">Details...</content></div>
<div id="container"><content/></div>
</div>
</template>
<handlers>
<handler event="click" phase="default-action">
this.open = !this.open;
</handler>
<handler event="DOMAttrModified" attr-name="open" attr-change="addition">
this.shadowTree.getElementById('container').setAttribute('state', 'visible');
</handler>
<handler event="DOMAttrModified" attr-name="open" attr-change="removal">
this.shadowTree.getElementById('container').setAttribute('state', 'hidden');
</handler>
</handlers>
<implementation>
({
get open() { return this.boundElement.hasAttribute('open'); },
set open(val) {
if (val)
this.boundElement.setAttribute('open', 'open');
else
this.boundElement.removeAttribute('open');
return this.open;
},
})
</implementation>
</binding>
</xbl>
In this specification, the term in error, typically used of an element or attribute, means that the element, attribute, or other construct is not conformant according to the rules of this specification. Rules for exactly how the element, attribute, etc, must be treated when it is in error are always given when the term is used. Typically this will involve ignoring the erroneous nodes, meaning the UA must, for the purposes of XBL processing, act as if those nodes were absent. UAs must not, however, remove such nodes from the DOM in order to ignore them. The nodes retain all their non-XBL semantics.
UAs should report all errors to users, although they may do this in an unobtrusive way, for example in an error console.
In addition to the error handling rules given in this specification, UAs may abort all processing when encountering an error.
Aborting is only likely to be a viable error handling mechanism in controlled environments, e.g. in conformance checkers. Web browsers are expected to use the error recovery mechanisms described in this specification, not abort.
A correct element, attribute, value, or binding is one which is not in error.
The following sample XBL document is in
error because the script
element in XBL is only allowed as a child of the xbl element:
<xbl xmlns="http://www.w3.org/ns/xbl"> <binding id="demo"> <script> // This example is in error. // You are not allowed to put ascriptelement inside // abindingelement, only inside anxblelement. // This is because scripts evaluate in the scope of the // entire XBL document, and are therefore not associated // with a particular binding. function life() { return 42; } </script> </binding> </xbl>
The correct way of doing this would be:
<xbl xmlns="http://www.w3.org/ns/xbl">
<script>
// This example is correct.
function life() {
return 42;
}
</script>
<binding id="demo">
<!-- Now you can see that this binding actually does nothing. -->
</binding>
</xbl>
The namespace of all the XBL elements and
XBL global attributes must be (this is a
temporary namespace): http://www.w3.org/ns/xbl
XBL elements are frequently referred to by just their local name in this specification. In real documents, they must be associated with the XBL namespace as per the rules given in the Namespaces in XML specification [XMLNS].
For convenience, elements and attributes from specific namespaces are
sometimes referred to simply in the form prefix:localname,
without explicitly stating which namespace the prefix is bound to. When
this occurs, readers should assume the following prefix declarations are
in scope:
xmlns:xbl="http://www.w3.org/ns/xbl" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:html="http://www.w3.org/1999/xhtml"
When this specification refers to elements in a namespace, it does not exclude elements in no namespace; the null namespace is considered a namespace like any other for the purposes of XBL processing.
All element names, attribute names, and attribute values in XBL are case sensitive.
An XML MIME type is text/xml,
application/xml, or any MIME type ending with the string
+xml (ignoring any MIME parameters).
1.2. Conformance
As well as sections marked as non-normative, all diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in [RFC2119]. For readability, these words do not appear in all uppercase letters in this specification.
User agents may optimize any algorithm given in this specification, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms. (The algorithms in this specification are generally written with more concern over clarity than over efficiency.)
XBL subtrees must satisfy the constraints described in this specification.
An XBL user agent is an implementation that attempts to support this specification.
XBL user agents must behave as described by this specification, even when faced with non-conformant XBL subtrees.
This specification is defined in terms of the DOM. The language in this specification assumes that the user agent expands all entity references, and therefore not include entity reference nodes in the DOM. If user agents do include entity reference nodes in the DOM, then user agents must handle them as if they were fully expanded when implementing this specification. For example, if a requirement talks about an element's child text nodes, then any text nodes that are children of an entity reference that is a child of that element would be used as well.
1.2.1. Attributes Containing Selectors
The element attribute of the binding element and the includes
attribute of the content element, if
specified, must be parsed according to the rules in the Selectors
specification. [SELECTORS]
This specification does not specify what level of Selectors support is required.
Namespace prefixes can be used with selectors. In XBL attributes that
take selectors, the namespace prefixes that may be used are the prefixes
that are in scope using the xmlns:* syntax. User agents must
use the XML namespace prefixes in scope on the attribute's element when
parsing selectors with namespace prefixes. The default namespace in
selectors in XBL attributes is always unbound ("*"). [XMLNS]
The following excerpt from an XBL document defines a binding that is
bound to elements declaring links (e.g. the a
element in HTML).
<xbl xmlns="http://www.w3.org/ns/xbl"> <binding element=":link, :visited"> ... </binding> </xbl>
The following excerpt defines a binding bound to any element in the
http://example.com/ namespace that is the child of an
element in the http://www.example.net/ namespace with the
name parent. (Note that the > character
does not have to be escaped.)
<xbl xmlns="http://www.w3.org/ns/xbl"
xmlns:eg1="http://www.example.net/"
xmlns:eg2="http://example.com/">
<binding element="eg1|parent > eg2|*">
...
</binding>
</xbl>
Finally this third example defines a binding that matches elements
with the name blockquote, regardless of what namespace they
are in. If it is known that the binding document is only ever going to
be used from documents that use one namespace, for example if the
bindings are always to be imported into HTML documents, then it is
easier to just specify the tag name (as in this example) and ignore the
namespaces.
<xbl xmlns="http://www.w3.org/ns/xbl"> <binding element="blockquote"> ... </binding> </xbl>
1.2.2. Attributes Containing Space-Separated Values
Some attributes are defined as taking space-separated values. The list of values for such attributes must be obtained by taking the attribute's value, replacing any sequences of U+0020, U+000A, and U+000D characters (in any order) with a single U+0020 SPACE character, dropping any leading or trailing U+0020 SPACE character, and then chopping the resulting string at each occurrence of a U+0020 character, dropping that character in the process.
A space-separated attribute whole value is either the empty string or that consists of only U+0020, U+000A, and U+000D characters has no values.
In the attribute button="1 2", the values are "1" and
"2".
In the attribute
class=" key - note - rocks",
there are five keywords: "key", "note", "rocks", and two occurrences of
the single-character keyword "-".
1.3. Security Concerns
This section is non-normative.
XBL raises a number of security concerns.
Data theft: A naïve implementation of XBL would allow any document to bind to bindings defined in any other document, and (since referencing a binding allows full access to that binding document's DOM) thereby allow access to any remote file, including those on intranet sites or on authenticated extranet sites.
XBL itself does not do anything to prevent this. However, it is strongly suggested that an access control mechanism (such as that described in [ACCESSCONTROL]) be used to prevent such cross-domain accesses unless the remote site has allowed accesses.
Privilege escalation: In conjunction with data theft, there is the concern that a page could bind to a binding document on a remote site, and then use the privileges of that site to obtain further information. XBL prevents this by requiring that the bindings all run in the security context of the bound document, so that accessing a remote binding document does not provide the bound document with any extra privileges on the remote domain.
Cookie theft: Related to privilege escalation is the
risk that once an access-controlled binding document hosted on a remote
site has been loaded, authentication information stored in cookies for
that domain would become accessible to the bound document. XBL prevents
this by requiring that the cookie attribute on the
DocumentWindow interface be set to null.
Secure bindings: Using XBL for bindings that need access to the local filesystem, e.g. for implementing File Upload form controls, is not yet handled by this specification. However, a future version will provide a secure way to define an XBL binding that can be used to implement privileged mechanisms that can then be used by other bindings to provide such controls.
1.4. Relationship to XBL1
This specification is not backwards compatible with XBL1.
There are numerous changes. However, of particular importance to
readers familiar with XBL1, there have been some changes to the element
names. In particular, the XBL1 element content is
now called template, and the XBL1
element children is now called content.
1.5. Relationship to XSLT
This specification has a similar scope to XSLT. The main differences are:
-
XSLT operates on a static DOM, permanently replacing that DOM for rendering. XBL, on the other hand, transparently transforms the DOM for rendering while leaving the underlying structure intact, and dynamically reflects changes to the underlying DOM in the transformed rendering.
-
XSLT allows any arbitrary transformation to be performed. XBL shadow trees, on the other hand, only support reordering of the bound element's child nodes and interleaving of those explicit children with shadow content. Arbitrary transformations are not possible in XBL while retaining the transparent nature of XBL's shadow tree processing.
In addition, XBL can be used for component creation, which is not covered by XSLT.
2. XBL Elements
The start of any XBL subtree is an xbl
element, which is described below.
When an XBL element is found inside an element other than those listed as its "Expected contexts", it is in error. When an XBL element has a child node that does not satisfy the "Expected children" list in its definition (for instance because it is the wrong node type, wrong element type, or because too many elements of its type preceded it), the child is in error. In both cases, being in error means that the UA must, for the purposes of XBL evaluation, treat the XBL subtree as it would if the erroneous node and all its descendants were not present in the DOM.
However, non-XBL elements retain their semantics, even when considered to be in error for the purposes of XBL.
For cases where unexpected attributes are found on XBL elements, or XBL attributes are found on elements other than those listed as the "Expected context", the error handling is similar: the attributes must be considered to be in error and the UA must ignore them, meaning that the presence of unexpected attributes in no way affects the XBL processing.
Further error handling rules for more specific cases are given where appropriate.
XBL user agents that support CSS should act as if they had the following rules in their UA style sheet:
@namespace xbl url(http://www.w3.org/ns/xbl);
xbl|* { display: none; }
xbl|div { display: block; }
XBL user agents that do not support CSS should not render the XBL
elements other than the div element,
which they should render as a paragraph-like element.
2.1. The xbl Element
- Expected contexts:
- In an XBL document, none
(this is the root element).
- In a non-XBL document, any non-XBL element whose specification allows the
xblelement as a child. - In a non-XBL document, any non-XBL element whose specification allows the
- Expected children (in any order):
binding: zero or more.script: zero or more.- Any non-XBL element.
The xbl element is the root element of
all XBL subtrees.
Attributes
- id
- The
idattribute. - script-type
- The
script-typeattribute specifies the MIME type of the scripting language used by all bindings and XBL script blocks in the XBL subtree. If the attribute is not specified, the default language is ECMAScript. [ECMA262] - style-type
- The
style-typeattribute specifies the MIME type of the styling language used by all bindings and XBL style blocks in the XBL subtree. If the attribute is not specified, the default language is CSS (text/css).
UAs must consider any xbl elements
that have another xbl element as an
ancestor as being in error and must
then ignore them, meaning those
elements must never be considered to declare any bindings. For example,
UAs must never bind elements to bindings defined by binding elements that have two xbl ancestors.
Similarly, XBL elements (other than the xbl element itself) that do not have a correct xbl
element as an ancestor are in error
too, and UAs must ignore them,
treating them as they would any arbitrary semantic-free XML element. For
example, UAs must never bind elements to bindings defined by binding elements that have no xbl ancestors at all.
The same does not apply to the style-type and script-type attributes. If the UA does not
support the specified styling language, it must still apply bindings as
appropriate; only style blocks must be
ignored. Similarly, if the UA does not support the specified scripting
language, it must still apply bindings as appropriate; only script, handler and implementation sections must be
ignored.
The empty string is not a special value for these
attributes. Setting the style-type attribute to the empty string,
e.g., will result in all style blocks
being ignored, since the empty string is not a valid MIME type that the
UA supports.
The following document defines two bindings, one using Perl as the
scripting language and the other using JavaScript. The second one
extends the first one. (This example assumes that
text/x-perl refers to Perl. Note that this specification
doesn't actually define how Perl-based bindings are to be supported by
the UA; the code below assumes that an implementation element takes an
anonymous Perl package and blesses a hash to that package for each
binding, but this is nothing but conjecture.)
<root>
<xbl xmlns="http://www.w3.org/ns/xbl"
script-type="text/x-perl">
<binding id="validityImplementor">
<implementation>
use strict;
use vars qw(@ISA);
@ISA = qw(XBLImplementation);
sub validate {
my $self = shift;
my $data = $self->{boundElement}->getAttribute('value');
my $pattern = $self->{boundElement}->getAttribute('pattern');
return $data =~ m/^(?:$pattern)$/s;
}
</implementation>
</binding>
</xbl>
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="validityClassifier" extends="validityImplementor">
<handlers>
<handler event="change">
if (this.baseBinding.validate())
this.boundElement.className = 'valid';
else
this.boundElement.className = 'invalid';
</handler>
</implementation>
</binding>
</xbl>
</root>
(What these bindings do is somewhat boring. The first does nothing
except expose a "validate()" method that returns true if the contents of
the element's value attribute matches the regular
expression in the element's pattern attribute. The
second makes the binding call this method every time the change event bubbles through the element, and changes
the element's class attribute based on the return
value.)
2.2. The binding Element
- Expected context:
xbl- Expected children (in any order):
implementation: zero or one.template: zero or one.handlers: zero or one.resources: zero or one.- Any non-XBL element
The binding element describes a
single XBL binding that adds presentation and interactive behavior to
XML or HTML elements. Each binding has these optional components:
Methods, Properties, and Fields: A binding can specify additional methods that can be invoked on the element. It can also specify additional properties and fields that can be retrieved or set on the element. In this way the functionality of the bound element becomes extensible. (See: binding implementations.)
Template: The optional template defines the initial shadow content for the bound element.
Behavior: A binding
can define event listeners for various types of events. Some examples
are: UI events (e.g., key and mouse events) on the bound element or on
elements within the shadow content; mutation events on the bound element
and its descendants; and events having to do with XBL's binding
operations (e.g., the binding and
bound events). (See: event
handlers.)
Resources: A binding can list style sheets that are scoped to the bound element, and images, sounds, videos, or other files that a user agent can pre-cache in order to improve performance. (See: binding style sheets, prefetching resources.)
Bindings may act as an attachment mechanism, specifying a namespace and
local name of elements to associate with the given binding when the
binding is imported, using the element
attribute.
In addition to the above, the binding element's child nodes may include
any element outside the XBL namespace. These are handled as they would be
in any other context, and are ignored by the XBL processing model.
Attributes
- id
- The
idattribute. - extends
- The
extendsattribute is used to specify the URI of a binding that this binding inherits from. (See: interpretation of URIs to XBL bindings.) If the URI is in error or does not refer to another binding, the UA must ignore it, meaning that this binding does not explicitly inherit from another binding. (See: explicit inheritance.) - element
-
This attribute specifies a selector. All elements in the binding document, and in any documents that import the binding document, that match the given selector, must be bound to the binding defined by this
bindingelement. (The element's own shadow tree, if any, must not be taken into account when determining if it matches a selector for the purposes of this attribute.)If an
elementattribute contains an invalid selector, it is in error and must be ignored, meaning that while the binding is still parsed and may be referenced using other attachment mechanisms, the binding is not attached to any element by itselementattribute, as if the attribute had simply been omitted.
The binding element defines a
presentation and behavior binding. It does not define an element's
semantics. If an element has no semantics when processed alone, then it
has no semantics when processed with XBL.
Sending markup that does not have well-defined semantics over the network is bad practice. XBL is intended to be used to augment the user experience, for instance by providing better quality widgets or prettier presentation. If the document being sent is unusable without XBL, then XBL is being abused.
This binding extends a binding defined in an external file. The
binding in the other file defines a value
property, and fires events when that property is changed. This
binding just implements a check box that all checkbox
elements in the http://ui.example.com/ namespace will be
bound to.
<xbl xmlns="http://www.w3.org/ns/xbl"
xmlns:ui="http://ui.example.com/">
<binding element="ui|checkbox" id="checkbox"
extends="http://www.example.org/resources/ui-core.xml#valuedControl">
<template>
<div id="wrapper">
<div id="checkbox"/>
<div id="label"><content/></div>
</div>
</template>
<resources>
<style>
#wrapper > div { display: inline-block; }
</style>
</resources>
<handlers>
<handler event="click" phase="default-action">
if (this.baseBinding.value == 'on')
this.baseBinding.value = 'off';
else
this.baseBinding.value = 'on';
</handler>
<handler event="change" phase="target">
if (this.baseBinding.value == 'on')
this.shadowTree.getElementById('checkbox').textContent = '☑';
else
this.shadowTree.getElementById('checkbox').textContent = '☐';
</handler>
</handlers>
</binding>
</xbl>
2.3. The implementation Element
- Expected context:
binding- Expected children:
- If the element has no
srcattribute: depends on the styling language.- If the element does have a
srcattribute: none. - If the element does have a
The implementation element
describes a set of methods, properties, and fields that are attached to
the bound element. Once the binding is attached, these methods,
properties, and fields can be invoked directly from the bound element.
The implementation element,
if present, must either contain code in the language specified by the XBL
subtree's script-type attribute, or have a src attribute
that points to a resource containing code in the language specified by
the script-type attribute. The syntax and
semantics of this code depend on the specific language. This
specification defines the semantics for ECMAScript implementations. (See: binding implementations.)
Attributes
- id
- The
idattribute. - src
- The
srcattribute specifies the URI to a resource of the type given by the XBL subtree'sscript-typeattribute. If the attribute is specified, the contents of the element must be ignored (even if the resource could not be fetched or was of the wrong type). (See: binding implementations.)
If an implementation
element is marked (via the script-type attribute of the xbl element) as being in a language that the UA
does not support, or, if the implementation element points (using
the src
attribute) to a resource that is either unavailable, or not of the type
specified by the script-type attribute of the xbl element (or implied by its absence), then it
is in error and the UA must ignore it, meaning it must not be used as an
implementation definition for any binding.
How UAs must handle nodes inside implementation elements depends on the
language used. (See: loading and running
scripts, binding
implementations.)
implementation blocks are
evaluated once, on first use. Changes to an implementation element or its contents
have no effect once the element has been evaluated. (See: binding implementations.)
User agents may support an additional attribute with the name
vendor-binary (e.g. moz-binary="" or
khtml-binary="") that contains information on native code
implementations of the binding, if necessary.
The following example shows a binding that defines a new method, two new properties (one with a custom getter and setter, one without), an internal field (used to back the property), and some hooks to initialize the binding and to handle the bound element being inserted and removed from the document. The binding applies to any element with the class "demo" (in the files into which it is imported, that is).
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding element=".demo">
<implementation>
({
add: function (op1, op2) {
return op1+op2;
},
get memory() {
return this._memory.toString();
},
set memory(value) {
this._memory = parseInt(value, 10);
},
xblBindingAttached: function() {
this._memory = 0; // private property to back "memory" public property
this.public.state = 'initialized'; // public property
},
xblEnteredDocument: function() {
this.public.state = 'in document';
},
xblLeftDocument: function() {
this.public.state = 'out of document';
},
})
</implementation>
</binding>
</xbl>
The get field() {} and
set field(syntax) {} features are part
of JavaScript 1.5 and will probably be in ECMAScript 4.
The following example shows how to refer to an external file for the implementation of a binding. In this example, the handlers simply defer to methods defined in that implementation, so that all the code is in that file.
<xbl xmlns="http://www.w3.org/ns/xbl"> <binding id="demo"> <implementation src="demo.js"/> <handlers> <handler event="click"> this.clicked(event); </handler> <handler event="focus"> this.focused(event); </handler> <handler event="blur"> this.blurred(event); </handler> </handlers> </binding> </xbl>
The demo.js file for this might look like this, to ensure
that the methods defined are in fact internal methods, not exposed on
the public object:
({
xblBindingAttached: function () {
this.clicked = function (event) { ... };
this.focused = function (event) { ... };
this.blurred = function (event) { ... };
},
// ... other methods and fields ...
})
2.4. The template Element
- Expected context:
binding- Expected children:
- Anything. Of particular interest, the
contentandinheritedelements may occur as descendants, and non-XBL descendant elements may hostxbl:inheritsandxbl:pseudoattributes.
The template element contains
child nodes that can be in any namespace. The subtree specified by the
template element is referred to as
the shadow content template. When a binding is
attached, the template element's
child nodes are cloned and attached to the bound document under the bound
element. Because these cloned nodes are hidden from their parent and
exist outside the normal document tree, they are referred to as shadow content. (See: rules for shadow content generation.)
Dynamic changes to shadow content templates are reflected in bindings. (See: shadow content.)
Attributes
- id
- The
idattribute. - apply-author-sheets
- The
apply-author-sheetsattribute indicates whether or not rules in author style sheets associated with the bound element's document apply to the shadow content generated by the binding. Its value must be eithertrue(indicating that they do) orfalse(indicating that they do not). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is to not apply the bound document's author style sheets (same asfalse). (See: binding style sheets.) - allow-selectors-through
- The
allow-selectors-throughattribute indicates whether or not rules in CSS can cross scopes. Its value must be eithertrue(indicating that they can) orfalse(indicating that they cannot). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is to not let selectors cross scopes (same asfalse). (See: selectors and shadow scopes.)
The semantics of non-XBL elements inside this element are untouched, which can lead to unintuitive results. (See: semantics of non-XBL elements in XBL contexts.)
The following binding defines a shadow tree that wraps the contents of
the bound element in four blocks. It uses the apply-author-sheets attribute to
allow the bound document to style the nodes directly, and uses the allow-selectors-through
attribute to allow the bound document to pretend (for the purposes of
selector matching) that the shadow tree actually is descended from the
bound element.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="wrapBy4">
<template apply-author-sheets="true" allow-selectors-through="true">
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<div class="wrap4">
<content/>
</div>
</div>
</div>
</div>
</template>
</binding>
</xbl>
Using this binding could take the following document:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pretty Title</title>
<style>
h1 span { display: block; }
h1 { border: solid red; }
h1 .wrap1 { border: solid orange; }
h1 .wrap2 { border: solid yellow; }
h1 .wrap3 { border: solid green; }
h1 .wrap4 { border: solid blue; }
</style>
</head>
<body>
<h1>
<span class="wrap1">
<span class="wrap2">
<span class="wrap3">
<span class="wrap4">
Pretty Title
</span>
</span>
</span>
</span>
</h1>
...
</body>
</html>
...and shrink it to this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pretty Title</title>
<style>
h1 { -xbl-binding: url(cool.xml#wrapBy4); }
h1 { border: solid red; }
h1 .wrap1 { border: solid orange; }
h1 .wrap2 { border: solid yellow; }
h1 .wrap3 { border: solid green; }
h1 .wrap4 { border: solid blue; }
</style>
</head>
<body>
<h1>Pretty Title</h1>
...
</body>
</html>
...which removes the semantic-free elements used as presentation hooks from the content markup layer, and places them in the presentation layer where they belong.
2.5. The content Element
- Expected context:
- Any, but there must be a correct
templateelement somewhere in the ancestor chain, and there must not be any correctcontentelements anywhere in the ancestor chain. - Expected children:
- Anything.
The content element is used inside
shadow content to specify insertion
points for explicit children that
might already exist underneath the bound element. As far as the
presentation model is concerned, any shadow content the binding places
between the bound element and the content elements is interleaved between the
bound element and its explicit
children without affecting the document model. (See: processing content
elements.)
If the includes attribute successfully matches
against children of the bound element, then those children are inserted
into the final flattened tree in place
of the content element. If the includes
attribute does not match against any children, then the child elements of
the content element are inserted
into the final flattened tree in place
of the content element instead.
Attributes
- id
- The
idattribute. - includes
- The
includesattribute can be used to indicate that only certain content should be placed at thecontentelement. Its value is a selector. (See: processingcontentelements.) - apply-binding-sheets
- The
apply-binding-sheetsattribute indicates whether or not scoped style sheets loaded for an XBL binding are applied to a bound element's explicit children (in addition to the bound element itself) that are inserted below thiscontentelement when it is processed. Its value must be eithertrue(indicating that they are) orfalse(indicating that they are not). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is that they are not applied (same asfalse). (See: binding style sheets.) - locked
- The
lockedattribute indicates whether or not new children may be inserted below thiscontentelement when it is processed. Its value must be eithertrue(indicating that they may not) orfalse(indicating that they may). The default behavior, which is used when the attribute is omitted or has a value other than the two allowed values, is that they may be inserted (same asfalse). Elements already assigned to acontentelement whoselockedattribute is dynamically changed are not removed from that element. (See: processingcontentelements.)
This sample extract from a binding document shows how to use the includes
attribute to distribute children to different parts of a shadow content
template.
<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
xmlns:data="http://example.com/data-language">
<xbl:binding element="data|grid">
<xbl:template>
<xbl:div class="caption" xbl:inherits="xbl:text=title"/>
<xbl:div class="outer-table">
<xbl:div class="columns">
<xbl:content includes="data|column">
<!-- default to have just one column if none are declared -->
<data:column/>
<xbl:/content>
<xbl:/div>
<xbl:div class="rows">
<xbl:content includes="data|heading"/>
<xbl:div class="body">
<xbl:content includes="data|row:not([hidden])"/>
<xbl:/div>
<xbl:/div>
<xbl:/div>
<xbl:/template>
...
<xbl:/binding>
...
<xbl:/xbl>
The above template would be used with markup such as the following:
<data xmlns="http://example.com/data-language">
...
<grid title="The Lesser of Two Evils">
<column id="product" sort="alphabetic primary"/>
<column id="catchphrase" sort="alphabetic secondary"/>
<heading>
<item>Product</item>
<item>Catchphrase</item>
</heading>
<row>
<item>Arachno Spores</item>
<item>The fatal spore with the funny name</item>
</row>
<row>
<item>Pastorama</item>
<item>Located on the former site of Brooklyn</item>
</row>
</grid>
...
</ui>
The following illustrates how the above markup would get redistributed.

In this example, the binding uses the apply-binding-sheets attribute
to let its stylesheet affect the explicit
children of the bound element.
<xbl xmlns="http://www.w3.org/ns/xbl"
xmlns:ui="http://example.org/ui-language/">
<binding element="ui|listbox">
<template allow-selectors-through="true">
<div id="listbox-focus">
<content includes="ui|listitem" apply-binding-sheets="true">
</div>
</template>
<resources>
<style>
@namespace xbl url(http://www.w3.org/ns/xbl);
@namespace uil url(http://example.org/ui-language/);
uil|listbox { display: block; background: white; color: black; }
uil|listbox > xbl|div#listbox-focus { border: ridge silver; }
uil|listbox:focus > xbl|div#listbox-focus { border: inset silver; }
uil|listitem { display: block; background: white; color: black; }
uil|listitem[selected] { display: block; background: navy; color: white;}
</style>
</resources>
...
</binding></xbl>
In the following example, the locked attribute is used to keep the children
of the bound element in the insertion point that the user has selected.
<xbl xmlns="http://www.w3.org/ns/xbl"
xmlns:ui="http://example.org/ui-language/">
<binding element="ui|duallist">
<template>
<div id="left">
<ui:listbox id="left">
<content includes="ui|listitem" id="leftList"/>
</ui:listbox>
</div>
<div id="buttons">
<ui:button id="move-right"> Move Right </ui:button>
<ui:button id="move-left"> Move Left </ui:button>
</div>
<div id="right">
<ui:listbox id="right">
<content includes="ui|listitem" locked="true" id="rightList"/>
</ui:listbox>
</div>
</template>
<implementation>
({
xblBindingAttached: function() {
this.shadowTree.getElementById('move-right').addEventListener(
'click', this.moveRight, false
);
this.shadowTree.getElementById('move-left').addEventListener(
'click', this.moveLeft, false
);
},
moveRight: function(event) {
this.shadowTree.getElementById('right').setInsertionPoint(
this.shadowTree.getElementById('left').selectedElement
);
},
moveLeft: function(event) {
this.shadowTree.getElementById('left').setInsertionPoint(
this.shadowTree.getElementById('right').selectedElement
);
},
})
</implementation>
</binding>
</xbl>
2.6. The inherited Element
- Expected context:
- Any, but there must be a correct
templateelement somewhere in the ancestor chain. - Expected children:
- Anything.
The inherited element represents
an insertion point for the next inherited shadow tree. If the binding is
the base binding (and thus has no inherited bindings) or if none of the
bindings it inherits from have shadow trees, or if this is not the first
inherited element in the binding's
shadow tree, then the contents of the inherited element (if any) are used
instead. (See: rules for shadow content
generation.)
Attributes
- id
- The
idattribute.
While it is legal to nest inherited elements, it is pointless, since
if one inherited element used its
fallback content, any subsequent such elements will too.
The following binding wraps the bound element's children in a set of
divs for extra styling. By using the
inherited element, it has been
designed such that it must be used in conjunction with other bindings:
it will (if applied after the others) wrap the shadow trees of those
templates. Contrast this with the
example in the template section, which would not
interact with other bindings. However, if this binding is not applied in
conjunction with a binding that has an insertion point for the element
explicit children, then those children will not be in the final
flattened tree.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="wrapBy4">
<template apply-author-sheets="true" allow-selectors-through="true">
<div class="wrap1">
<div class="wrap2">
<div class="wrap3">
<div class="wrap4">
<inherited/>
</div>
</div>
</div>
</div>
</template>
</binding>
</xbl>
2.7. The xbl:inherits Attribute
- Expected element:
- Any, but there must be a correct
templateelement somewhere in the ancestor chain.
The xbl:inherits attribute is a global
attribute in the XBL namespace that specifies which attributes on the
bound element should be forwarded to the element on which the attribute
is found when the shadow content template is cloned. It is a space-separated list of QNames or QName
pairs separated by equal signs, each possibly suffixed by a hash
character ("#") and a type designation. (See: attribute forwarding.)
One of the major uses of the xbl:inherits attribute is to implement
one element in terms of another element which already has special
behavior in user agents. This example shows how a ui:text
element can be implemented in terms of an html:input
element, with certain attributes being forwarded to that element
directly.
<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
xmlns:ui="http://example.com/ui-language/"
xmlns:html="http://www.w3.org/1999/xhtml">
<xbl:binding element="ui|text">
<xbl:template>
<html:label>
<html:span xbl:inherits="xbl:text=label"/>
<html:input xbl:inherits="value=default disabled readonly" id="input"/>
</html:label>
</xbl:template>
<xbl:implementation>
({
get value () { return this.shadowTree.getElementById('input').value; },
set value (val) { this.shadowTree.getElementById('input').value = val; },
})
</xbl:implementation>
</xbl:binding>
</xbl:xbl>
2.8. The xbl:pseudo Attribute
- Expected element:
- Any, but there must be a correct
templateelement somewhere in the ancestor chain.
The xbl:pseudo attribute is a global attribute
in the XBL namespace that specifies the pseudo-element that, when used on
the bound element, must be mapped to the element on which the attribute
is found. (See: matching
pseudo-elements.)
The value of the xbl:pseudo attribute must be a a valid
pseudo-element name (without the leading "::"). The valid pseudo-elements
are "value", "choices", "label", "repeat-item", and "icon". Future
versions of CSS might introduce new values.
The xbl:pseudo attribute is useful as a way to
let author styles affect the insides of a shadow tree without exposing
the exact construction of the tree. Here, the binding represents a
composite widget with an icon, a label, a text field, and some buttons.
Pseudo-elements are used for each part allowing the author to style each
part separately.
<xbl:xbl xmlns:xbl="http://www.w3.org/ns/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<xbl:binding id="input-dialog">
<xbl:template>
<xbl:div class="root">
<xbl:div class="icon-block">
<html:img xbl:pseudo="icon" xbl:inherits="src=icon alt=alt"/>
</xbl:div>
<xbl:div xbl:pseudo="label" xbl:inherits="xbl:text=label"/>
<xbl:div class="field-block">
<html:input xbl:pseudo="value" xbl:inherits="value" id="field"/>
</xbl:div>
<xbl:div class="buttons-block">
<html:button xbl:pseudo="choices" id="ok"> OK </html:button>
<html:button xbl:pseudo="choices" id="cancel"> Cancel </html:button>
</xbl:div>
</xbl:div>
</xbl:template>
...
</xbl:binding>
</xbl:xbl>
An author-level stylesheet for a document using the binding might look like:
textDialog { -xbl-binding: url(dialogs.xml#input-dialog); }
textDialog::value { background: white; color: black; }
textDialog::choices { border: outset; }
2.9. The div Element
- Expected contexts:
templatecontentinheriteddiv- Expected children:
- Anything. Of particular interest, the
contentandinheritedelements may occur as descendants, and non-XBL descendant elements may hostxbl:inheritsandxbl:pseudoattributes.
The div element has no intrinsic
meaning. It is intended to be used as a styling hook for presentational
bindings.
Attributes
- id
- The
idattribute. - class
- A space-separated list of
keywords relevant to the element that could be useful as stylistic
hooks. This is a "class" attribute (which means, for example, that the
CSS "." shorthand can be used to match
divelements based on theirclassattribute). Theclassattribute doesn't apply to other XBL elements, only todiv. - state
- A free-form attribute with no predefined meaning that can be used as a stylistic hook, to store state, or for other purposes as desired by the binding author.
- title
- Text representing advisory information that the user agent should
show to the user upon request (e.g., on a graphical browser, the
contents of this attribute could be shown as a tooltip when the user
indicates the element with a mouse pointer). The
titleattribute doesn't apply to other XBL elements, only todiv.
The div element in XBL is not
the same element type as the div element
in HTML, but it is intended to be used in similar ways (and shares the
name for that reason).
Many of the examples in this specification use the div element.
The following example uses the state attribute so that the CSS style sheet can
render the shadow tree differently based on whether the switch that the
binding represents is turned on or off.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="switch">
<template>
<div class="wrapper">
<div id="main" state="off"/>
</div>
</template>
<handlers>
<handler event="click">
this.shadowTree.getElementById('main').setAttribute('state',
this.shadowTree.getElementById('main').getAttribute('state') == 'on' ?
'off' : 'on');
</handler>
</handler>
<resources>
<style>
#main[state=off] { ... }
#main[state=on] { ... }
</style>
</resources>
</binding>
</xbl>
2.10. The handlers Element
The handlers element's event
handlers can be called for events that flow through the bound element.
During capture, target, bubbling, and default phases, when a given event is
received by a bound element, if a corresponding event listener has been
attached to the handlers element,
then the event will be forwarded to that event listener. (See:
event forwarding, binding attachment and detachment.)
Typically, event handlers are defined using handler elements.
Attributes
- id
- The
idattribute.
The following example shows how handlers can be used with any old event
listener mechanism.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="test">
<handlers id="test-handlers"/>
...
</binding>
<script>
document.getElementById('test-handlers').addEventListener('click', function (event) {
// this will get called for every click event that bubbles through
// any element that is bound to the "test" binding above.
...
}, false);
</script>
</xbl>
2.11. The handler Element
- Expected context:
handlers- Expected children:
- Depends on the scripting language.
The handler element describes a
single event handler. This handler is attached to its parent handlers element, which is used as an event
forwarding target when handling events on the bound element. (See:
event handlers.) It wraps a script
that is executed when the event handler is matched.
Attributes
- id
- The
idattribute. - event
- The
eventattribute describes the specific event that this handler is listening for. (See: registering event handlers with thehandlerelement.) - phase
- This attribute specifies the phase of the event flow that this
handler should monitor. The possible values are
capture,target,bubble,default-action. Ifcaptureis specified, then the event handler must only be fired during the capturing phase of event propagation. Iftargetis specified, then the event handler must only be fired during the target phase. Ifdefault-actionis specified, then the event handler must only be fired during the default phase (if it occurs). Otherwise, the handler must only be fired during the bubbling phase. (See: registering event handlers with thehandlerelement.) - trusted
- This attribute specifies whether the handler should be limited to
trusted events. The possible values are
trueandfalse. Iftrueis specified, then the event handler must only be fired if the event'strustedattribute is true. Otherwise, the value of thetrustedflag does not affect the event handler. (See: registering event handlers with thehandlerelement.) - propagate
- The
propagateattribute specifies whether after processing all listeners at the current node, the event is allowed to continue on its path (either in the capture or the bubble phase). It has no effect if thephaseattribute has the valuedefault-action. (See: registering event handlers with thehandlerelement.) - default-action
- The
default-actionattribute specifies whether after processing of all listeners for the event, the default action for the event (if any) should be performed or not. (See: registering event handlers with thehandlerelement.) - button
- The
buttonattribute imposes a filter on the handler. It is used with mouse handlers to specify a particular button. (See: mouse event handler filters.) - click-count
- The
click-countattribute imposes a filter on the handler. It is used with mouse handlers to specify how many clicks must have occurred. (See: mouse event handler filters.) - modifiers
- The
modifiersattribute imposes a filter on key and mouse handlers. It is used with mouse and key handlers to specify particular modifier keys. (See: mouse event handler filters, key event handler filters, modifiers.) - key
- The
keyattribute imposes a filter on key handlers. It is used with key handlers to specify which keys to listen for. (See: key event handler filters.) - key-location
- The
key-locationattribute imposes a filter on key handlers. It is used with key handlers to specify which keys to listen for. (See: key event handler filters.) - text
- The
textattribute imposes a filter on text input handlers. It is used with text input handlers to specify which characters to listen for. (See: text input event handler filters.) - prev-value
- The
prev-valueattribute imposes a filter on mutation handlers. It is used with mutation handlers to specify whatprev-valueto listen for. (See: mutation event handler filters.) - new-value
- The
new-valueattribute imposes a filter on mutation handlers. It is used with mutation handlers to specify whatnew-valueto listen for. (See: mutation event handler filters) - attr-name
- The
attr-nameattribute imposes a filter on mutation handlers. It is used with attribute mutation handlers to specify which attribute to listen to for changes. (See: mutation event handler filters) - attr-change
- The
attr-changeattribute imposes a filter on mutation handlers. It is used with attribute mutation handlers to specify the type of change to listen for. (See: mutation event handler filters.)
If a handler element is marked
(via the script-type attribute of the xbl element) as being in a language that the UA
does not support then the UA must ignore it, meaning it must not be used for
the event handler definitions of any binding.
How UAs must handle nodes inside handler elements depends on the language
used. (See: loading and running
scripts, event handlers.)
handler blocks are evaluated each
time they are fired. Changes to the handler elements therefore take effect the
next time the an event is fired.
The following binding implements a link which, when clicked once with the primary button and with no key modifiers, or, when focused and sent a keypress of the Enter key with no modifiers, will cause the link to be followed.
It will only do this if the click or the keypress is a real event triggered by the user; it won't do it for events faked by script. However, if the event faked by script is a DOMActivate event, then it will follow the link, because the handler for the DOMActivate event doesn't check that the event is trusted. (If it did, it would never fire, because the event is dispatched by the binding, and therefore is not trusted.)
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="events">
<handlers>
<handler event="click" phase="default-action"
button="1" click-count="1" modifiers="none"
trusted="true">
this.activate();
</handler>
<handler event="keypress" phase="default-action"
key="Enter" modifiers="none"
trusted="true">
this.activate();
</handler>
<handler event="DOMActivate" phase="default-action">
if (event.target == this.boundElement)
this.boundElement.document.location.href = this.href;
</handler>
</handlers>
...
<!-- it is assumed that the implementation for this binding
implements a .activate() method that fires the DOMActivate
event on itself. -->
</binding>
</xbl>
2.12. The resources Element
- Expected context:
binding- Expected children (in any order):
style: zero or more.prefetch: zero or more.
The resources element contains a
list of style sheets to apply when using this binding, as well as a list
of files (images, videos, sound files, etc) to optionally preload.
Attributes
- id
- The
idattribute.
2.13. The style Element
- Expected context:
resources- Expected children:
- If the element has no
srcattribute: depends on the styling language.- If the element does have a
srcattribute: none. - If the element does have a
The style element is used to specify
a style sheet that is to be applied to the bound element and to the
shadow content generated by the binding, as well as to any explicit children (and their descendants)
assigned to insertion points in the shadow content whose apply-binding-sheets attribute is
set.
The style element in XBL never
applies styles to elements in the bound document other than the bound
element (and possibly its children, see below). It never affects any
ancestors of the bound element, or any nodes in any other bindings or
binding templates.
Attributes
- id
- The
idattribute. - media
- The
mediaattribute specifies the intended destination medium for style information. How the value of this attribute is interpreted is defined by Media Queries [MQ]. If this attribute is not specified, then there is no restriction on which media the style sheet should be applied to (same as specifyingmedia="all"). - src
- The
srcattribute specifies the URI to a resource of the type given by the XBL subtree'sstyle-typeattribute. If the attribute is specified, the contents of the element must be ignored (even if the resource could not be fetched or was of the wrong type). (See: binding style sheets.)
If a style element is marked (via
the style-type attribute of the xbl element) as being in a language that the UA
does not support, or, if the style
element points (using the src attribute) to a resource that is either
unavailable, or not of the type specified by the style-type
attribute of the xbl element (or implied
by its absence), then it is in error
and the UA must ignore it, meaning
it must not be used to style anything.
How UAs must handle nodes inside style elements depends on the language used.
(See: binding style sheets.)
For a summary of the various ways that content can be styled in the presence of XBL, see the styling summary section.
2.14. The prefetch Element
- Expected context:
resources- Expected children:
- None.
The prefetch element can be used
to list resources that may be pre-loaded for performance reasons. Support
for this element is optional. UAs may ignore it.
Attributes
- id
- The
idattribute. - src
- A URI to a resource (such as an image) that the binding might use later.
The following binding uses two images; it sets the source of an HTML
img element programatically to refer to those images. To
make sure the images are always available, it uses a couple of prefetch elements.
<xbl xmlns="http://www.w3.org/ns/xbl">
<binding id="light">
<template>
<html:img id="l" src="red.png"/>
</template>
<resources>
<prefetch src="red.png"/> <!-- this one isn't necessary, since
the UA will fetch this one as soon as it sees the <img> element -->
<prefetch src="green.png"/>
</resources>
<implementation>
({
red: function() {
this.shadowTree.getElementById('l').src = 'red.png';
},
green: function() {
this.shadowTree.getElementById('l').src = 'green.png';
},
})
</implementation>
</binding>
</xbl>
This binding might be used as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Light Demo</title>
<style>
#light { -xbl-binding: url(demo.xml#light); }
</style>
</head>
<body>
<p id="light">Red</p>
<p>
<input type="button" onclick="doRed()" value="red">
<input type="button" onclick="doGreen()" value="green">
</p>
<script>
var light = document.getElementById('light');
function doRed() {
light.textContent = "Red";
if (light.red)
// binding might not be applied, so only call the method if it is defined
light.red();
}
function doGreen() {
light.textContent = "Green";
if (light.green) // same
light.green();
}
</script>
</body>
</html>
Ok, so this example is a little far fetched. So are most of the examples in this spec. They're just examples!
2.15. The script Element
- Expected context:
xbl- Expected children:
- If the element has no
srcattribute: depends on the styling language.- If the element does have a
srcattribute: none. - If the element does have a
The script element contains code
that is executed when the XBL subtree is loaded. It can therefore be used
to define helper functions used by the bindings.
The script element, when present,
must either contain code in the language specified by the XBL subtree's
script-type attribute, or have a src attribute that
points to a resource containing code in the language specified by the
script-type attribute. The syntax and
semantics of this code depend on the specific language. (See: loading and running scripts.)
Attributes
- id
- The
idattribute. - src
- The
srcattribute specifies the URI to a resource of the type given by the XBL subtree'sscript-typeattribute. If the attribute is specified, the contents of the element must be ignored (even if the resource could not be fetched or was of the wrong type). (See: loading and running scripts.)
If an script element is marked (via
the script-type attribute of the xbl element) as being in a language that the UA
does not support, or, if the script
element points (using the src attribute) to a resource that is either
unavailable, or not of the type specified by the script-type attribute of the xbl element (or implied by its absence), then it
is in error and the UA must ignore it, meaning it must not be executed.
How UAs must handle nodes inside script elements depends on the language used.
(See: loading and running scripts.)
script blocks must be evaluated
when their end-tag is parsed, or, for dynamically created elements, when
they are first inserted into a document. This is the case whether or not
the elements are in
error.
Once evaluated, a script block is
dead and changes to its contents or attributes have no effect.
2.16. The id Attribute of XBL Elements
- Expected element:
- Any element in the XBL namespace.
The id attribute
assigns a name to an element. This name must be unique in the binding document. The id attribute is of type ID. [XML].
If the attribute's value is the empty string, the attribute must not set an ID. Otherwise, the attribute's value must be treated as (one of) the element's ID(s).
3. Resources
3.1. Loading External Resources
Several features in XBL allow external resources to be loaded.
When the specification says that the resource must be loaded unless it has already been loaded, then references to the same resource (even if they are somewhat indirect, for example via HTTP redirects) must result in the same instance being reused, or shared. To determine if two resources are the same, their final base URIs (after all redirects) are compared.
A binding document A contains a
binding element that refers to a
second binding document X. A new DOM Document instance is
created to represent that instance and the relevant bindings are used.
Now assume RX is a resource that redirects to resource X using the
HTTP 301 redirection mechanism. A second binding element in the binding document A
refers to resource RX. When that resource is being loaded, the redirect
to X would be discovered, and therefore instead of creating a new
Document, the existing one is reused.
Such resource sharing is limited to resources loaded by a document, its binding documents, its scripts, and its style sheets. Nested documents and images do not share resources with each other or with their container document.
Resources that are currently loading count as resources that are already loaded for the purposes of this reuse mechanism.
For example, if a document uses a binding document, and its style
sheets use that binding document, the same binding document instance
will be used for both cases. However, if that document contains an
iframe whose document uses the same binding document, a new
instance will be used: the binding document instance from the outer
document is not reused.
When the specification simply says that the external resource must be loaded, without giving any caveats regarding multiple accesses of the same resource, then each reference must instantiate a new unique copy of the document.
For example, two style elements whose src
attributes point to the same style sheet must create two different
Stylesheet instances, such that mutating one does not affect
the other.
Several XBL attributes are defined to contain URIs. All URIs may be relative. For relative URIs, the rules given in [XMLBASE] must be used to resolve the value to an absolute URI.
3.2. Loading and Running Scripts
Scripts in XBL may be found in script, implementation, and handler elements, or in resources that those
elements point to.
In the case of script and implementation
elements, if a src attribute is present then the
contents of the element must be ignored (even if
fetching the specified URI fails).
The rules for parsing the scripts are the same for all three elements, but depend on the scripting language specified by the author.
For non-XML languages, if the content is inline, UAs must concatenate all the textual contents of text and CDATA child nodes, and must ignore any other, non-text nodes (such as elements and comments) along with all their children. All descendant elements must be processed, though, according to their semantics, before the XBL script block itself is executed.
For example, in an XHTML-aware and ECMAScript-capable user agent, the
following ridiculous code would cause the alerts to appear in the order
One, Two, Three, and would set the test property
in the binding document's global script scope to the string
"undefinedABC":
<xbl xmlns="http://www.w3.org/ns/xbl">
<script>
alert('Two');
test += "B";
<script xmlns="http://www.w3.org/1999/xhtml">
alert('One');
test += "A";
</script>
alert('Three');
test += "C";
</script>
</xbl>
Authors must not ever consider doing this.
For XML-based scripting languages, handling of unknown elements and unexpected nodes must be defined by that language.
If the content is not inline, then when the element is evaluated, the
resource specified by the src attribute must be
fetched. For script elements, while
an external script is being fetched, any pending binding attachments
from the same binding document must block, as must the evaluation of any
further script blocks. For implementation elements, while the
external script is being fetched, the attachment of that binding must
block.
If the content is specified as being in a file, and that file's
Content-Type (or equivalent for non-HTTP protocols), if any, is of the
type specified on the xbl element, then the contents of that file must
be used directly, as spe