Welcome!

AJAX & REA Authors: Lee Novak, Brad Abrams, Alin Irimie, Jonny Defh, RealWire News Distribution

Related Topics: AJAX & REA

AJAX & REA: Article

Real-World AJAX Book Preview: Navigation Bar as a Template

Real-World AJAX Book Preview: Navigation Bar as a Template

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

Navigation Bar as a Template
Refer to TopNavBar.html. This is a pure HTML document. It's created to act as a template for the navigation bar. Note the "id" assigned to each anchor element. The screenshot of the navigation bar template is shown below.

Loading the Navigation Bar Template
We created MainPage-1.html and TopNavBar.html. This step shows how the navigation bar created by TopNavBar.html is loaded from the server and attached to its placeholder element in the MainPage-1.html. Refer to the MainPage-3.html for the following discussion.

The body element of the page specifies the JavaScript function to be invoked after the page is loaded by the browser. It's specified as the "onload" event handler - onload="initialize()."

<body bgcolor="white" onload="initialize()" style="height:480px; padding:0px;
margin:0px">
... ... ...
</body>

The "initialize()" method bootstraps the execution of the JavaScript code on the client side. The code executed by this method in the MainPage-3.html is simply to call another function, "loadTopNaviagation()."

function initialize() {
       loadTopNaviagation ();
}

The function "loadTopNaviagation" is defined in TopNavBar.js and is shown below.

function loadTopNaviagation() {
     // construct request
     var req = new DataRequest(serverURL + ‘TopNavBar.html',
       requestCompletedNavigationBar,
       requestFailedNavigationBar,
       requestTimedoutNavigationBar);
     // send the request to the server.
     ajaxEngine.processRequest(req);
}

If the request succeeds, the server returns TopNavBar.html as an XML document to the client. The callback method "requestCompletedNavigationBar" constructs the HTML DOM using the HTML passed in the result, retrieves the "topNavigationBar" element from it (see the TopNavBar.html), and attaches to the "NavBarArea." The end result is the following HTML page shown.

The complete code for the "requestCompletedNavigationBar" is shown below.

function requestCompletedNavigationBar(response) {
   // retrieve ‘topNavigationBar' element from the response.responseText
     // and attach it to the NavBarArea
     topNavBarElement = setElementFromHtml(response.responseText,
         ‘NavBarArea',
         ‘topNavigationBar');
     // create NavBar component
       navBar = new NavBar();
     // associate NavBar component with the element
       navBar.setHtmlElement(topNavBarElement);
       // inform the MainPage that the top navigation bar has been loaded
       topNavBarTemplateLoaded();
   }

The callback method uses the "setElementFromHtml" method for attaching the "topNavigationBar" element of the template to the placeholder element "NavBarArea." This is an important method that is used often in the application. Its code is shown below. It's defined in the file Util.js.

Listing 5.7 - Placeholder Elements in HMTL

function setElementFromHtml(html, targetId, srcElementId) {
     // target element where to attach
     var target = document.getElementById(targetId);
     if (target == null) {
       alert("Target: " + targetId + " does not exists");
     return;
     }

     // a utility method in Util.js. It removes all children of the give node
     removeAll(target); // remove all children
     target.innerHTML = html; // set the template HTML. This will build HTML dom

     // look for the source element to be attached in the newly built DOM.
     var element = document.getElementById(srcElementId);
       // clear the target element once again
       removeAll(target);
       // now simply attach the source element
       target.appendChild(element);
       // return the source element
       return element;
     }

In Listing 5.7, the statement innerHTML=html builds an HTML DOM underneath the target element. Since the TopNavBar.html is designed as a standalone HTML, it might have other elements such as header and body elements. We are interested in the navigation bar element and want to discard other elements. The subsequent steps retrieve the reference to the source element, reattach it to the target element, and discard the rest of the DOM built from the template.

Navigation Component
The NavBar class implements the behavior of the navigation element. It's generic and provides commonly used operations. The code is shown in Listing 5.8. This code assumes that the anchor elements contained inside the given navigation bar element are the selectable items. The comment lines explain the operation supported by the navigation bar item. This shows how clean the separation of a View and its Controller is. The required behavior is implemented using JavaScript code, whereas the actual look-and-feel and layout of the navigation bar is specified independently using HTML and CSS.

Listing 5.8 - NavBar Class

/** Implements navigation bar behavior. */
function NavBar() {
     // list of selectable items (anchor elements)
     this.items = null;
     // the html element that acts as the container of the navigation bar
     this.topElement = null;
     // currently selected item
     this.currentSelection = null;
}

// associates the HTML element used fot the navigation bar with this component
NavBar.prototype.setHtmlElement = function(e) {
     this.topElement = e;
     this.items = new ElementCollection(e).getElementsIndexedById(‘A');
}

// given the id of an item, associates on click event handler.
// The handler is invoked when the user clicks on the item.
NavBar.prototype.setHandler = function(itemId, handler) {
     if (this.items[itemId]) {
         var self = this;
         var iid = itemId;
         this.items[itemId].handler = handler;
         this.items[itemId].onclick = function(event) {self.selectItem(iid); self.
items[iid].handler(event)};
     }
}

// Sets the given item as selected.
// De-selects any previously selected item (displays it using normal style)
// Selects the new item (displays it using selected style)
NavBar.prototype.selectItem = function(itemId) {
     var newSelection = this.items[itemId];
     if (newSelection == this.currentSelection) {
         return false;
     }
     if (this.currentSelection != null) {
         this.currentSelection.className = ‘HBarItem';
     }
     this.currentSelection = newSelection;
     if (this.currentSelection != null) {
         this.currentSelection.className = ‘HBarItemSelected';
     }
     return true;
}

Navigation Controller
The navigation controller is a set of event handlers that handle the navigation bar item "onclick" event. After the navigation bar template is loaded, the function "topNavBarTemplateLoaded()" of the MainPage-3.html is called as shown below.

function requestCompletedNavigationBar(response) {
     ... ... ...
     topNavBarTemplateLoaded();
}

The following lines attach event handlers to items in the toolbar. The event handler simply displays "not yet implemented." In the following sections we'll replace them with actual event handlers.

function topNavBarTemplateLoaded() {
     navBar.setHandler("projectList", notYetImplemented);
     navBar.setHandler("projectDetails", notYetImplemented);
     navBar.setHandler("projectMembers", notYetImplemented);
)

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Anil Sharma

Anil Sharma is a founder of Vertex Logic and architect of its AjaxFace product. He is working with Vertex Logic's customers and helping them deploy WEB 2.0 applications built using AjaxFace. These applications are in the areas of online printing, community WEB sites and social networking. He is driving future products of Vertex Logic. Prior to Vertex Logic, he was CTO and founder of Softrock Systems and Component Plus. There he built a model driven application platform using J2EE. His primary interests include user interface infrastructures and model driven applications. He is one of the contributors of the book "Real World AJAX - Secrets of the Master".

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.