Montag, August 22, 2005

JavaScript Behaviours

This technique has nothing (not yet) to do with AJAX because it is a general usable implementation for reusing JavaScript code for components. Also, this technique has also nothing to do with ASP.NET because it only uses the client-side (browser) available HTML objects and JavaScript. It will be the client side functionality for the upcoming AJAX controls and it fits perfectly into a server-side HTML controls framework that enables also the reusing of HTML code fragments.

General

HTML pages without any more than HTML offer only a limited functionality and allow only displaying information and filling out forms. As a result HTML pages are often extended by using JavaScript for handling input validation, reacting on clicks or bringing optical effects.

But when it comes to reuse once-written functionalities there is no built-in concept to HTML and JavaScript except the flat programming model of include files. Copying sourcecode around is the often used response to this weakness and leads to unsupportable huge web sites often too.

Proprietary behaviours

Both most used browsers, Internet Explorer from Microsoft and the Mozilla/Firefox from the Mozilla foundation, have both their own incompatible way to allow reusing JavaScript functions and HTML on a component level.

Common to both solutions is the big advantage over global script include files that the functionality is bound and accessible through a specific HTML object, can be bound to multiple objects and support specific methods, attributes and event handlers.

Lightweight, compatible behaviours

Building a cross-browser functionality that is very similar to the built-in behaviours of the browsers is not very hard to do.

It basically consists of defining new properties, specific methods and event handlers by building a JavaScript prototype object for each behaviour. Also a common binding functionality is needed that attaches these definitions to a HTML object after the page is loaded. Script include files can be used to bring the prototype objects into the pages.

A simple example

This is the HTML object

<div id="TimerSample" style="...">click here</div>

Here is a simple behaviour that is handling the onclick event and brings in a new update method that is changing the content of the bound HTML object:

var TimerSampleBehaviour = {
  onclick: function (evt) {
    evt = evt ||window.event; // get a compatible event object
    evt.srcElement.update();
  }, // onclick

  update: function() {
    var d = new Date();
    this.innerText = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
  } // update

} // TimerSampleBehaviour

The behaviour functionality must be bound to the HTML object by calling one method only:

LoadBehaviour(document.getElementById("TimerSample"), TimerSampleBehaviour);

The "magic" work behind the LoadBehaviour() method is to loop though all elements of the given JavaScript object and assigning each of them to the HTML object.:

  • Methods. Starting with "on" are assumed to be event handlers and are attached using the browser specific methods for attaching events. Only the bubbling phase of the event is used because it is implemented by both browsers.
  • Other methods are just bound to the HTML object as function objects.
  • All the other objects are assigned if there is not already an assigned property existing on the HTML object. These objects are shared for all HTML objects that are bound to the same behaviour.

We might expect more functionality from behaviours but this is a set of functionalities that are available in all the supported browsers.

This simple sample can be found on the sample website:

http://www.mathertel.de/AJAXEngine/ in Samples Part 2.

The relevant code can be found in the html page itself and in the include file cb.js.

Writing event handlers

Event handlers use a naming convention to be distinguished from object specific methods by starting with "on". The name of the function should always be lowercase and the function must have a single parameter holding the event object.

Because the IE is not passing the event object through the parameter of an event method we always need a first line to get a compatible event object:

evt = evt || window.event; // get a compatible event object

The clicked HTML object is available by using the srcElement property of the event object.

This is not a native property of Mozilla/Firefox but is made available using a specific patch that is also included – beside other patches – in the common include file cb.js.

I think that it’s a good idea not to implement much in these handlers but to call another method soon because the event handlers always expect an event object and therefore are not reusable for being called from other events or methods.

Writing methods

Writing a method for a behaviour is as simple as writing compatible JavaScript.

Properties or attributes as well as other methods of the bound HTML object are accessible by using the "this" object reference to the HTML object. Never call any method of the prototype object directly, they all are also available through "this".

To make it easy to write compatible JavaScript methods there are some extensions implemented in the common include file cb.js. Mozilla/Firefox has a very powerful extensibility concept that allows easily to define new properties to built-in objects and to control their usage. IE is far behind this point so I use this extensibility to bring IE specific properties to the Mozilla/Firefox platform. Details can be found in the common include file cb.js inline comments.

Defining default values

New properties on the behaviour objects need not to be defined; they just can be used – but always through "this". The properties that are used as parameters to define a aspect of the functionality can be assigned default values in 2 ways:

  • An attribute can be set on the HTML object
  • A property on the JavaScript prototype can be set to an initial value and is used if no attribute is already defined on the HTML object.

When defining complex objects (arrays, structures) inside the JavaScript prototype you have to pay attention to the fact that these objects are shared among all HTML objects using this prototype. If individual complex objects are needed it is better to create and assign them in the "init" method.

The init method

A method named "init" can be defined in the JavaScript prototypes to implement special needs after the methods, event handlers and properties are bound to the HTML object. This method is automatically called by the LoadBehaviour method.

When the "init" method is called it is not guaranteed that the whole page is already loaded and that all other behaviours are bound to their HTML objects. If you need this point in time you have to attach a special handler to the onload event of the page.

Links

The Mozilla/Firefox behaviours: http://www.mozilla.org/projects/xbl/xbl.html

The IE behaviours: http://msdn.microsoft.com/workshop/components/htc/reference/htcref.asp

Search for behaviours using Google: http://www.google.com/search?q=htc+filetype%3Ahtc

Sonntag, August 21, 2005

Application Aspects

The examples on AJAX I’ve published up to now, had to point out special aspects of the technical design and the implementation. They correspond to the "Bottom UP" method and are about the base components Javascript, XMLHTTP, XML and the asynchronous processing - the aspects That giva AJAX its name.

However, it is not the goal to play some technological games but to realize, improved or modernized a complete application with the assistance of the AJAX engine. The use of AJAX technologies fortunately does not need any principle proceeding at the level of the application but starts at the level of components.

Integration of AJAX components

In some cases we can integrated a functionality which is based on AJAX into an existing web application to better solve the problem of a component.

The LookUp example can be used e.g. in conventional web form and the background validating of the content of a HTML form can be guide the user before a regular positing of the form data.

The amount of JavaScript code that has to be loaded on the client is only about 18 kByte for the AJAX engine and the additional code for handling the selection list not very large.

It helps however to save a multiple this size since the data portion does not have to be sent completely to the client and the multiple reloading of the pages saves several times. AJAX based components particularly develop their largest advantages and it is importantly to have easy integrable components.

AJAX controls

When building new pages it is again a big advantage if the realization does not have to be made on each individual page on a very much detailed level. Here we prefer pre-fabricated components side by side with regular HTML objects to build up the final page.

To reach a high percentage of reusability those components are realized outside of the individual pages and are parameterized for their concrete usage.

HTML is used for the description of the appearance of the controls and JavaScript for the implementation of the behaviour. The binding of Javascript methods to the HTML objects is offerend by the Internet Explorer (*.htc) and by the Mozilla/Firefox (*.xbl) however in very different implementations that would lead into a double implementation. I use therefore a simple but compatible binding.

ASP.NET and AJAX controls

My choice to realize a collection of AJAX capable control falls on ASP.NET and the built-in user controls. These components are easy to implement and adapt. They offer already enough possibilities compared with Web Controls that must be implemented as classes. In addition to ASP.NET 1.1 they can also be compiled completely with ASP.NET 2,0

Building a complete new framework is not my intention because there are already some very useful frameworks that permit building component-based web applications.

Because the controls to be implemented are substantially based in HTML and JavaScript they do not really use the ASP.NET functionalities available on the server. Only building up the HTML code of a page from components will needed and this can also to be done by other tag libraries of other environments.

The advantage of ASP.NET is beside that is the simple realization of Web services.

Donnerstag, August 11, 2005

Model View Controller (MVC) Pattern

Thinking about the structure and the layering of the components of solutions is important for software architects. It’s about getting the right distance to a concrete implementation, detecting the principles and unnecessary deviations.

Sometimes those thoughts exceed this range and lead into almost religious discussions about holy principles.

Discussing the Model-View Controller (MVC) is one of those topics that describes the distribution of objects and functionalities of a application with a user interface on a high level. There are books about I and a also the material on the web is very detailed.

Because AJAX style applications is for many developers a new kind of modeling web applications I have collected some of my thought on this topic.

Here I want to look and analyze the existing AJAX Engine and not build a ideal optimal AJAX architecture.

Definition of MVC

There are many different definitions for the Model-View-Controller Pattern (google it). I stay with the short one that can actually be found at Wikipedia: http://en.wikipedia.org/wiki/Model-view-controller

  • Model: This is the domain-specific representation of the information (data and methods) on which the application operates.
  • View: This renders the model into a form suitable for interaction, typically a user interface element.
  • Controller: This responds to events, typically user actions, and invokes changes on the model or view as appropriate.

Model

The Model part of the architecture all is relatively easy to discover in the WebServices. Here all functional aspects should be discoverable. There are of course also functional aspects in the User Interface but this code is implementing a more comfortable way of interaction and handles topics of the presentation.

Based of the role this code takes over in the whole architecture some typical aspects very similar to the SOA architecture of the model can be identified. Here some keywords:

  • Independent of HTML objects
  • No culture or language specific implementations
  • Manipulating and storing data
  • Stateless
  • Checking and securing of the parameters of the webmethods.
  • Reliable algorithms and functionalities

View

The View part can be localized in the realization of the User Interface by using HTML objects and some supplement JavaScript methods.

The base functionality of the HTML objects like editing values in input fields is covering a lot but also a lot of the Javascript implementation in the pages of my samples for example the LookUp List and displaying graphics is part of the view.

  • UI Events
  • Active elements like input fields
  • Layout elements and decorative additions
  • Converting of numbers and date formats to strings
  • Methods to support the working

Controller

But where is the Controller part in a AJAX application and how does it work ?

A simple answer is obvious: The AJAX Engine. Beside the WebService and the HTML there are only the script include files left to implement this part. The proxy methods for the webservices can be defined as part of the network infrastructure.

Page Controller

When comparing the traditional ASP.NET Web Forms with the MVC pattern the page-controller term is used very often. When comparing the 2 most used approaches ASP.NET and Struts you can easily detect that the server side implementation only covers the collaboration of the objects of a single page.

The transitions between the pages are not really supported with a structure by ASP.NET 1.1. Hyperlinks or Redirect statements are used on the server and some problems have to be solved for transferring information from one page to the next one. With ASP.NET 2.0 it is possible to have 2 pages in memory at once and transferring data is easier to implement but this is no solution for controlling the global flow of a web application.

Struts mixes up both aspects what may end in complex struts-config.xml files.

Both approaches for realizing web applications are described and compared regarding the MVC pattern in http://msdn.microsoft.com/library/en-us/dnaspp/html/ASPNet-ASPNet-J2EE-Struts.asp as well as in http://struts.apache.org/userGuide/building_controller.html.

When realizing an AJAX application the controller is shifted to the client and is implemented in JavaScript. Like with ASP.NET is can control only the activities of the one loaded page because all local information is lost when navigation to another page and a new UI and controller is built up. This is the reason why some AJAX applications have only one active URL using a complex page or framesets.

I have to compare this situation with the 2-tier application architecture of the 90’s. Here the controller also was implemented on the (fat) client and the server added data and methods (SQL connections and stored procedures).