| By Anil Sharma | Article Rating: |
|
| April 11, 2007 08:00 AM EDT | Reads: |
2,670 |
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.
Change Set for Server-Client Interaction
When the user makes changes to the data, all the changes can be recorded locally up to some point or sent to the server immediately. It depends on the application situation. In a typical application, there are certain changes that are buffered until the user selects an operation to indicate "save." There are other changes that immediately trigger a call to the server. In either case, the client can compute the changes and send the change set to the server. The local cache is also useful for the computation of the change set.
Message Format for Server Invocation
In our illustrations, the client and server use XML messages for data exchange and service invocation. A message sent by the client to the server identifies:
- Service Name: Identifier of the target server component
- Method Name: Actual operation to be invoked on the server
- Parameters: Parameters of the service.
- XML Document: Represents an arbitrarily complex structure that might have to be passed from the client to the server. As an example, the client passes change sets of edits made by the user over a long period.
- The name of customer "00001" is changed to "ABC Corp."
- The phone number of customer "00002" is changed to "768-340-1267."
- The description and quantity of order "2" of customer "00002" are changed.
// service-specification
<Service name="Customer">
<method name="update">
</Service>
// XML document passed in the body of POST method
<ChangeList>
<customer id="00001">
<name>ABC Corp</name>
</customer>
<customer id="00002">
<phone>768-240-1267</phone>
<order id="2">
<description>Folders</description>
<qty>400</qty>
</order>
</customer>
</ChangeList>
As long as the server and client have an agreement on names/identifiers, the message can be correctly interpreted. The messages sent by the server to the client are result datasets. We've already discussed the format of datasets.
Metadata
We've seen how the application data is represented and exchanged. There are cases, especially when implementing certain data-driven behavior, when we need to know the characteristics of the data or its metadata. For example, we may need to know the class specification of a business object. Such metadata can also be passed as XML messages. Standards bodies such as the Object Management Group (OMG) provide schemas for metadata. The problem is that they are overly complex to
follow. You can typically define a schema for metadata based on high-level knowledge of UML and the domain. The XML below offers example metadata for a class.
Listing 5.4 - Metadata for a Class
<Class name="Customer">
<attribute name="id" type="String" unique="true">
<attribute name="name" type="String" unique="true">
<attribute name="phone" type="String">
... ... ...
... ... ...
<association name="orderlist" type="one-to-many" toClass="Order">
<association name="corporateAddress" type="one-to-one" toClass="Address">
... ... ...
... ... ...
</Customer>
View
Next we'll unravel the sub-components of a view. The basic unit of an AJAX view is an HTML element such as input field, text area, and table. At the final stage, a view is an HTML document, i.e., a hierarchical collection of HTML elements. This hierarchy is referred to as a Document Object Model (DOM). Menus, toolbars, trees, tables, forms, tabs, and dialogs are various types of views. Each of these is a hierarchical structure of HTML elements. For example, a form contains labels and fields. DOM provides a set of APIs to access its structure and manipulate it using JavaScript. This capability is leveraged by the AJAX UI to render the UI on the client side as opposed to getting an entire page from the browser each time. In some cases, it's used to affect changes in the HTML document retrieved from the server. In other cases the entire page can be rendered in the client space.
A DOM can be constructed programmatically in JavaScript. Alternatively, it can be constructed from an HTML file. It's this feature of an AJAX UI, which makes it possible to construct a DOM from HTML, that makes it unique compared to other rich client technology. You can find equivalents of DOM in other rich client technologies. For example, the component hierarchy of Swing and the control hierarchy of WinForms are equivalent to DOM. But what they don't have and AJAX UI does is a tag language as powerful and well understood as HTML.
To recap, the features that make an AJAX UI a compelling rich client technology are:
- HTML and CSS are used to build views that are cleanly separated from the rest of the code. AJAX uses pure HTML devoid of any technology-specific tags that have to be pre-processed as in the case of server-side technologies such as JSP, JSF, and ASP.
- The AJAX UI can fetch data and superimpose on the top of the baseline view. It eliminates the need to fetch a new page every time and results in a responsive UI.
- To be able to add behavior (controller) using a scripting language (JavaScript) enables a dynamic architecture.
- The browser makes it ubiquitous.
So far we've identified an HTML element and HTML templates as two sub-components of a view. To get a functioning UI, we have to superimpose data and behavior on top of the HTML hierarchy. What does that mean? Well, superimposing data simply means changing the value of the HTML elements. For example, change the value of cells of the table to populate a table or change the value of the field elements to populate a form. Superimposing behavior means adding event handlers to the elements and implementing code for them. For example, an input element can behave like an integer field if a key event handler is added to it that disregards non-numeric values. We can abstract all such behavior in a JavaScript class (function). In the above example, input HTML element and associated JavaScript code together can be called an "Integer Component." The set of such abstractions, called component, is the third part of a view. In subsequent sections we'll demonstrate, using example codes, how to build a component.
To re-emphasize concepts, we'll describe these three sub-components of a view in more detail below.
HTML Elements and DOM
The HTML elements are the basic units of an UI. A collection of these elements constitutes a user view. Internally, in the browser space, the elements are represented as a Document Object Model (DOM). DOM depicts an element containment hierarchy in tree form. The DOM API allows for accessing and manipulating the DOM tree. Any manipulation of the DOM tree results in changes in the view rendered by the browser. For example, if the "display" attribute of an element is set to "hidden", that element is removed from the display. Not only that, but an entirely new DOM tree can be constructed using JavaScript. The key aspects of an AJAX UI are the ability to access DOM trees, manipulate them, and build new DOMs in the browser space using JavaScript. These capabilities let an AJAX client fetch application data from the back end and render the UI in the browser space. This is analogous to building a component hierarchy in a Swing UI or control hierarchy in a WinForms UI. It's superior to both Swing and WinForms technologies because:
- Constructing a professional-quality UI using HTML and CSS is simpler than constructing a Swing component or WinForms control hierarchy. The best part is that a UI designer can do it and, as a matter of fact of matter, it's already being done. Note, you don't need any JavaScript programming for this part.
- Superimposing data on top of the HTML document using JavaScript is no more difficult than programming in Basic and populating the data in WinForms controls (barring a lack of tools, a problem that will be addressed in due course). If done as a combination of CSS and DOM programming, AJAX is much more flexible. For example, implementing something like "If a value is greater than a million, show the value in a bold large red font." In other technologies, you'd do this programmatically for each attribute. In the case of DOM and JavaScript programming it will probably be done by assigning a new style class to the element. This is much more flexible since the style can be changed through a CSS file. This is one simple example. There are many more complex things such as showing heterogeneous rows in a table that are easier done in DOM plus JavaScript than in Swing or WinForms.
- Writing controller logic in JavaScript is the same as writing it for a WinForms UI in Basic or a Swing UI in Java. It's not much different to be considered simpler or harder (barring tools supports and the knowledge of a programming language). Here too, after getting into finer details, it can be argued that the DOM and JavaScript combination is a superior programming model. DOM provides a better API for accessing the elements' name space and manipulating their states.
- Compared to writing controllers on the server side as with a conventional Web UI programming model, an AJAX UI is orders of magnitude simpler.
A single aspect of the AJAX UI programming model, which makes it far superior to other rich UI technologies, is the capability of using HTML as templates.
Here is how this works: Create an HTML or, better, ask a UI designer to create an HTML and use some placeholder for the data. Give meaningful names to HTML elements or assign IDs. Now you can write simple JavaScript code to fetch data from the back end and replace the placeholder data with actual data. Let's take a look at another scenario. Write an HTML template to work like a tile for other pages and define placeholder block elements for sub-pages. Write sub-pages as separate HTML documents. At runtime, it's easy to fetch tile-page, sub-pages, and attach sub-pages to the tile-page using JavaScript. This provides a flexible tile in the form of an HTML document; change it, or move things around independent of the rest of the code as long as the names or identifiers of the elements are retained. It will work beautifully. It tosses complex programming models such as Struts, JSP, ASP, and JSF out of the window (at least for any greenfield initiatives).
Components
A component is a JavaScript class (this is a function that, in reality, can be treated like a class) and encapsulates the behavior of an HTML element giving it a special flavor. An element and its corresponding component class can be associated at runtime using JavaScript. For example, an "IntComp" can be associated with an "input" element to give it the flavor of an integer field. The main responsibilities of a component class are:
1. Data Binding: A component class defines "setValue" and "getValue" to display the value inside the element and retrieve the value from the element. For a simple component, it directly sets the value of the associated element. For a complex element, it sets the value of the sub-elements by calling the "setValue" method of the contained component class or by setting the value of the sub-elements directly. For example, elements of a form may have associated components. Setting the value of a form by passing an object instance as the value might call the "setValue" of the contained component by matching the name of the component with the attribute name of the passed object. In the case of a data grid, the "setValue" method might programmatically add rows ("tr" elements) and cells ("td" elements) for each row. The code snippet below shows how an element and a component class can be associated using JavaScript code and how the value of the component is set.
... ... ...
var e = document.getElementById('age');
var age = new IntComp();
age.setHtmlElement(e);
... ... ...
The following call will display a value of "40" inside the element "age."
age.setValue(40);
Don't worry about the actual implementation of the IntComp class and its methods. We'll get into their details in the following sections.
2. Implementing Specific Behavior: Beside data binding, a component class is responsible for implementing specific behavior and providing convenience methods. For example, a table may implement behavior for highlighting a row when a user clicks on it. Or, it can provide a convenience method such as "getSelectedRow."
Alternative to HTML Templates
We have seen that HTML elements are created by loading an HTML template associated with components. An alternative way is to create HTML elements programmatically instead of loading an HTML template. A combination of these two concepts: a) using HTML as a template and associating them with component classes and b) constructing HTML elements and component classes programmatically is extremely powerful. The former provides ultimate flexibility in generating any arbitrary layout using full features of HTML or CSS. A UI designer can do it. The latter provides a cookie cutter for a large number of routine UI components such as Forms, Tables, and Dialogs. Even if you start with an HTML template for the latter, it's easy to see common patterns and abstract them as cookie-cutter JavaScript code. Once this technique is mastered, all talk about a new tag language, or even a WYSIWYG editor, is futile.
List of Component Classes
For completeness we have listed some commonly used abstractions that may require a component class per abstraction. An application may need a subset of these. Or, for a special situation, you may need a component type, which isn't listed here.
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.
Published April 11, 2007 Reads 2,670
Copyright © 2007 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
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".
- Kindle 2 vs Nook
- Cloud Computing on Gartner's Top 10 List and SYS-CON Events' 2010 Calendar
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Moving Your RIA Apps into the Cloud: Seven Challenges
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Windows 7 – Microsoft’s First Step to the Cloud
- Ulitzer Provides a Powerful Social Journalism Platform
- Jill Tummler Singer, Deputy CIO of CIA, Keynotes at GovIT Expo
- Open Source Mobile Cloud Sync and Push Email
- Kindle 2 vs Nook
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing on Gartner's Top 10 List and SYS-CON Events' 2010 Calendar
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- US Post Office Hops a Ride on NetSuite’s Cloud
- Moving Your RIA Apps into the Cloud: Seven Challenges
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Building a Drag-and-Drop Shopping Cart with AJAX
- What Is AJAX?
- Google Maps! AJAX-Style Web Development Using ASP.NET
- Flashback to January 2006: Exclusive SYS-CON.TV Interviews on "OpenAjax Alliance" Announcement
- AJAXWorld Conference & Expo to Take Place October 2-4, 2006, at the Santa Clara Convention Center, California
- AJAX Sponsor Webcasts Are Now Available at AJAXWorld Website
- How and Why AJAX, Not Java, Became the Favored Technology for Rich Internet Applications
- "Real-World AJAX" One-Day Seminar Arrives in Silicon Valley
- AJAXWorld University Announces AJAX Developer Bootcamp
- AJAX Support In JadeLiquid WebRenderer v3.1
- Where Are RIA Technologies Headed in 2008?
- Struts Validations Framework Using AJAX





































