You are reading O'Reilly XForms Essentials by Micah Dubinko. (What is this?) - Buy XForms Essentials Online

Ways to Extend

The designers of XForms put lots of thought into ways of making the design flexible enough to be customized at all the critical points. The following sections describe areas where XForms has explicitly been designed to be extended.

It's true that XForms eliminates the need for a great deal of scripting. But not all. This is a good thing, since any system that could replace an entire scripting language (and associated libraries) would end up nearly as complicated as what it tried to replace—or worse. Instead, if a system replaces the 20% of the most commonly used functionality, it can still eliminate 80% of the need for script.

XForms doesn't include a script element to hold any script—that's a job for the host language. Typically, a script will be called as a result of XML Events processing, as described in Chapter 7, Actions and Events.

The XML-centric design of XForms influences the way script access to data works. Since a form at all times has a well-formed bit of XML behind it, represented by an XPath data model, script authors have a natural and familiar data structure with which to manipulate the form data. Availability of DOM access isn't a given—there's no requirement for an implementation to be based on the DOM. In fact, of the existing XPath engines, they seem to be split fairly evenly between DOM-based and not. However, in implementations that support the DOM, a special function callable from a script returns a DOM document representing the form data, which can be read, manipulated, and updated. As with other DOM interfaces, these methods are available from the scripting object representing the model element in question.

Generally, after changes have been made to the DOM document retrieved from getInstanceDocument( ), the rest of the system can be updated with a sequence of calls to rebuild( ), recalculate( ), revalidate( ), and refresh( ). Overall, the code tends to look something like the following JavaScript.

var modelElem = document.getElementById("id_of_model_element");
var instDoc = modelElem.getInstanceDocument("id_of_instance_element"); 

// Perform manipulations on instDoc here ...

modelElem.rebuild(  );
modelElem.recalculate(  );
modelElem.revalidate(  );
modelElem.refresh(  );

Each of the four methods perform a slightly different task.

As can happen in the standards process, having four separate methods to accomplish this provides a finer level of detail than nearly any form author would ever need. To tidy up your code, you might consider defining a single function to handle it all, like this:

function fullUpdate( elem, structure_changed ) {
  if (elem) {
    if (structure_changed)
      elem.rebuild(  );
    elem.recalculate(  );
    elem.revalidate(  );
    elem.refresh(  );
  }
}