Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JavaScript for the MVC example

, January 01, 2002


WebReview.com: The DOM in Version 5 Browsers

The DOM in Version 5 Browsers

Rank: 2

W3C DOM

In the "Netscape Now!" tradition, I've created a new animated button to signify that this document complies with the W3C DOM. The gryphon was originally designed by John Tenniel, for Alice in Wonderland. Use this button free of charge on pages that adhere to the W3C's DOM standard.

Version 5 browsers from Microsoft and Netscape will support the World Wide Web Consortium's new standard Document Object Model (DOM), as Michael Floyd explained in his Feb. 1, 1999, article, "DOM and DOMer." (Netscape Navigator 5.0, also known as Gecko, is currently in beta.) This should make it easier to develop dynamic web pages that work in most browsers, without having to code for both makes of browser.

This article offers a quick view of some the incompatibilities in how the Version 4 browsers interpreted the DOM, along with a look at how the Version 5 browsers handle it differently.

We also discuss the model-view-controller design paradigm, which the DOM aspires to. MVC has become important to user-interface programming because it emphasizes a design discipline that maintains separation between content and layout.

Since some developers are understandably impatient to embark on the possibilities offered by this new architecture for web pages, we offer a simple dynamic document that shows how to change the contents of a web page through the DOM.

Finally, we offer a description of the World Wide Web Consortium's DOM standard, for those who may not be familiar with it, or who could benefit from a refresh.

Version 4 incompatibility

Incompatibilities between Netscape Navigator 4 and Microsoft's Internet Explorer 4.0 center around Microsoft's sweeping ability to make HTML elements in the document accessible to the programmer. It's no coincidence that Microsoft uses the keyword "all" to describe its collection of exposed elements. For example, to change the text content of an element with a given ID to the value strnewtext, one writes

document.all[id].innerHTML = strnewtext

Netscape Navigator 4, by contrast, is largely limited to writing new HTML into a temporary file, and then loading that document into a frame-like object called a layer. Note that the Layer tag isn't often used explicitly in Netscape DHTML documents, but its creation is implied behind the scenes, since any valid application of Cascading Style Sheets positioning to an object spawns a new layer to contain it. The corresponding Netscape code looks like this:


          var lyr = document.layers[id].document
          lyr.open()
          lyr.write(strnewtext)
          lyr.close()

To produce Version-4 cross-browser DHTML, then, one creates a "fork," a single module whose behavior is switched by the detection of either browser, like this:


        ns4 = (document.layers)? true:false
        ie4 = (document.all)? true:false

        function simpleLayerWrite(id,text) {
         if (ns4) {
          var lyr = document.layers[id].document
          lyr.open()
          lyr.write(text)
          lyr.close()
         }
         else if (ie4) document.all[id].innerHTML = text
        }

Version 5 compatibility

Now, what's different in Version 5? It's actually quite a big deal. Netscape Navigator 5.0 supports its Layer model only for backwards compatibility, and Internet Explorer 5.0 supports its "all" keyword for the same reason. Instead (at the risk of oversimplifying and sounding too optimistic), both browsers allow you to modify the document content dynamically by changing the elements of the exposed document tree using the common DOM API, as you'll see.

A cautionary note about Netscape 5.0: It's a huge undertaking that's seriously behind the original schedule. The Mozilla engineers have committed to a goal of full compliance with all W3C web publishing standards, but month after month the browser has continued to exhibit holes in essential aspects of DOM manipulation. If you try to learn the DOM by relying on the Gecko browser instead of Microsoft's (as I have) you are setting yourself up for frustrating and baffling challenges.

A dynamic document

The DOM is a Java and JavaScript application program interface (API). Using the document object model API, you can create, modify, and destroy HTML objects at will.

Here's an example. You'll need Internet Explorer 5 or Netscape's experimental Gecko browser to see it in action.

And here's the code:

<!-- [email protected] -->
<!-- Monday, May 31, 1999 v.01 -->
 <HEAD>
  <TITLE>Dynamic Table</TITLE>
   <SCRIPT SRC="mvctable.js"></SCRIPT>
 </HEAD>
 <BODY>
  <IMG SRC="w3cdom.gif" ALT="W3C DOM"> 
(Use this page only in Version-5 Netscape or Microsoft browsers.) <br />A simple demonstration of the model/view/controller pattern and<br /> the use of the W3C's standard Document Object Model. Test<br /> (1) <i>first</i>, and <i>then</i> (2).<BR>
  <INPUT TYPE="button" ID="whosaid" ONCLICK= "javascript:<br /> refreshView(arraysources);" VALUE="1. Who said?"><BR>
  <INPUT TYPE="button" ID="goaway" ONCLICK= "javascript:<br /> destroyView();" value="2. Go away"><BR>
 </BODY>
</HTML>

Listing 1. A dynamic table for Microsoft Internet Explorer 5 and Netscape Navigator 5.0.

At first glance, this HTML document looks like the pages we've been writing for several years. It has some perfunctory text and two pushbuttons.

But when the page actually loads in a Version 5 browser, we see that it also contains a table of familiar quotations from characters in Alice's Adventures in Wonderland. Since these features are created only when the page loads, and can be altered dynamically without reloading the browser, we can call this dynamic HTML (DHTML).

The buttons alter the content dynamically. Click the "Who said" button, and the quotations are replaced by the names of their sources. Click the "Go away" button, and the table is destroyed, along with the buttons themselves.

The buttons' "onclick" handlers are connected to two custom-built JavaScript methods, refreshView() and destroyView(), found in an external JavaScript file, mvctable.js.

The model-view-controller pattern

This page illustrates a kind of user interface that embodies the model-view-controller (MVC) design pattern. MVC occupies a central role in application design today.

It's an unfortunate coincidence that the word "model" appears in both "model-view-controller" and "Document Object Model"; the word means different things in each. MVC refers to a data source as the data model, and to the current contents of the display as the data view.

The relationship between these two programming disciplines (MVC and DOM) is a bit like the difference between strategy and tactics.

  • Your strategy—whether you are working in Smalltalk (where the MVC design paradigm was invented) or in Java/Swing (where MVC rose to prominence) or in JavaScript (where you push documents around)—should be to separate content from layout.
  • The tactics vary from tool to tool. In HTML, DOM is a new tactic for achieving that goal. This means to separate content from layout.
  • that just because you can do magic tricks on documents with the DOM API, it doesn't mean you have mastered the zen of MVC—and vice versa.

Since the goal of object-oriented programming is to encourage code standardization and reuse, an MVC application is factored into reusable models and views. For instance, in this case, the model consists of a standard JavaScript array and the view consists of a standard HTML table. Methods to manage a data array and to build HTML user-interface components can be made recyclable.

MVC emphasizes separation between content and presentation, thereby encouraging the same content to be displayed on devices with different capabilities. For example, on some browsers, list items may appear in an elaborate interactive list box, but very small devices might only be able to render lists as bullet text. In a world where PCs may soon no longer dominate digital communications, an MVC discipline is essential to avoiding the maintainance of multiple sets of content (read: whole web sites) tailored to each kind of user. Moreover, an MVC design discipline helps to avoid desynchronization between a local cache of data being modified by the user and the actual data source. The MVC pattern was used everywhere throughout Gecko's design.

Code that synchronizes the model with the view is called the controller, and it is not generally reusable. This scheme is shown in Figure 1.

Figure 1
Figure 1. The model-view-controller design pattern.

In this extreme example, the view object is responsible only for display, it doesn't even handle the user input, contrary to what one might expect from software components such as list boxes that handle their own selection. Rather, the controller captures user input and sends it to both the database and the view object. Regardless of the details, the real objective is to keep the tiny data window belonging to the view in sync with changes occuring to the data model.

Now let's take a look at the JavaScript that runs our example. After that, we'll offer a short look at the W3C's DOM standard.


JavaScript for the MVC example
Understanding the Document Object Model


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.