topics: functional programming, concurrency, web-development, REST, dynamic languages

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, July 4, 2008

Manual code specialization:a poor-mans partial evaluation in JavaScript

Recall the object function that Douglas Crockford is promoting in his work on prototypal inheritance in JavaScript:

function object(p) {
function F(){}
F.prototype = p;
return new F();
}

The object function creates a new object which has the input object (p) as it's prototype.

On the comp.lang.javascript newsgroup Richard Cornford showed a functionally equivalent version which has better performance in general:


var object = (function(){
function F(){}
return function(p){
F.prototype = p;
return new F();
};
})();


In this version, all invocations of object share the same F which has its prototype mutated with each call. Cornford argues:


[The first version of 'object']... is an example of the process that clearly expresses what is being done, but is not particularly efficient as it creates a new - F - function each time it is executed, but all of those - F - functions are essentially identical. If this is to be done often then a more efficient approach would be to only create a single - F - function and put it where it could not be modified by external code.


Now, it is important to notice that in general one has to be careful when applying this technique to recursive functions as a variable mutation in one level of recursion may affect others. Also, if we were to put threads into JavaScript, this code would go from being thread-safe in the original form to non-thread safe in the optimized form. However, for now, this technique can be applied in performance-critical functions.


In fact, there is a general technique here that one might call code specialization via higher-order functions (which can be seen as a poor-mans form of partial evaluation). Here is a simple example of that general technique: The 'mk_tag' function creates the string for an html tag with a class attribute and a text-contents.


function mk_tag(tag_name,clazz,contents) {
return '<'+tag_name+' class="'+clazz+'">'+contents+'</'+tag_name+'>';
}


Using code specialization via higher-order functions (by currying), we can make specialized functions for writing e.g. 'div' tags, and specialized (faster) functions for making 'div' tags with certain classes. The trick is to compute as much as is possible with the given inputs before returning the specialized function:


//a curried version which specializes to it's input
function curried_mk_tag(tag_name) {
var tag_hd = '<'+tag_name+' class="',
tag_tail = '</'+tag_name+'>';

return function(clazz) {
var head = tag_hd+clazz+'">';
return function(contents) {
return head+contents+tag_tail;
}
}
}

var mk_div = curried_mk_tag("div")
var mk_div_green = mk_div("green")
var mk_div_blue = mk_div("blue")
mk_div_green("karl")//<-- "<div class="green">karl</div>"
mk_div_blue("karl")//<-- "<div class="blue">karl</div>"


This is elegant as functions can be reused, e.g., 'mk_div_green("karl");mk_div_green("krukow")'. But notice that it is more efficient than simply using a general currier (e.g., Diaz); essentially it is a form of manual partial evaluation.


I'll post some performance measurements in a later posting, but initial results show that we can reduce execution time by roughly 40% by using the sharing form of the object function.


More Examples


I'm not sure how many JavaScript programmers are familiar with this type of optimization. Here are a bunch of real-world examples where it can be applied:

Prototype - Ajax.request function

var Ajax = {//original
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},

activeRequestCount: 0
};

The thing to notice here is that every time getTransport is called prototype will recompute which XMLHttp transport to use. However, the result of Try.these will always be the same in a particular run of Prototype, i.e., the showing of a page in one browser. So we might as well precompute which object is the correct one:

var Ajax = {//modified form
getTransport: Try.these(
function() { new XMLHttpRequest(); //test if it exists
return function() {return new XMLHttpRequest();}
},
function() { new ActiveXObject('Msxml2.XMLHTTP'); //test
return function() {return new ActiveXObject('Msxml2.XMLHTTP'); }
},
function() { new ActiveXObject('Microsoft.XMLHTTP');
return function() {return new ActiveXObject('Microsoft.XMLHTTP'); }
}),

activeRequestCount: 0
};


jQuery - attr function

//original...
attr: function( name, value, type ) {
var options = name;

// Look for the case where we're accessing a style value
if ( name.constructor == String )
if ( value === undefined )
return this[0] && jQuery[ type || "attr" ]( this[0], name );

else {
options = {};
options[ name ] = value;
}

// Check to see if we're setting style values
return this.each(function(i){
// Set all the styles
for ( name in options )
jQuery.attr(
type ?
this.style :
this,
name, jQuery.prop( this, options[ name ], type, i, name )
);
});
}


With jQuery we can't write a curried form as that would break compatability. However, we can still perform optimizations like what we had with the 'object' function. Notice that the function supplied to 'each' is created with each invocation of 'attr', you can also see a for-loop where a check to 'type' is made with each iteration. In our optimized version, attr chooses which inner function to give to 'each' by checking type first.

//modified form
jQuery.fn.attr = (function(){
var type,
options,
inner_type = function(i){
// Set all the styles
var t = type,
s = this.style;
for (var name in options ) {
jQuery.attr(s,
name,
jQuery.prop( this, options[ name ], t, i, name )
);
}
},
inner_no_type = function(i) {
for (var name in options ) {
jQuery.attr(this,
name,
jQuery.prop( this, options[ name ], null, i, name )
);
}

};

return function( name, value, t ) {
type = t;
options = name;
// Look for the case where we're accessing a style value
if ( name.constructor == String )
if ( value === undefined )
return this[0] && jQuery[ type || "attr" ]( this[0], name );

else {
options = {};
options[ name ] = value;
}

// Check to see if we're setting style values
return this.each(t ? inner_type : inner_no_type);
};
})();

Thursday, June 12, 2008

fun with with


WARNING: After reading this blog you may start playing around with the evil 'with' statement in JavaScript. It's actually quite fun, but note that I'm not encouraging it's use in general.

In a previous blog I advocated the use of namespacing in JavaScript programs. To support namespacing I presented a pair of functions 'namespace' and 'using'. The former introduces a namespace, e.g.,

namespace({
com:
trifork:
tribook: ['model','view','controller']});

ensures that object 'com' exists with a property 'trifork' which in turn has a property 'tribook', etc. The using function brings such a 'package' or 'module' object into scope. For example

using(com.trifork.tribook.model,
com.trifork.tribook.view).run(function(model,view){

var meet = new model.Room('meeting 1');

});

Now, in the last couple of months I have been working in several projects using these functions, and I feel they have really helped me structure the JavaScript code -- one project has several thousands of lines of JS code structured in files and modules mirroring the package structure (i.e., dk.ourclient. ...). In these projects, a usage pattern occurs. Many files started:

namespace('dk.ourclient.supernavigator.controller');

using(dk.ourclient.supernavigator.view,
dk.ourclient.supernavigator.model,
dk.ourclient.supernavigator.controller).run(function(v,m,c) {

c.ContactController = function(spec) {
//... m.xxx, v.yy
};

});

I was annoyed with the WET (i.e. as opposed to DRY) repeated occurrence of 'dk.ourclient.supernavigator'. One alternative pattern would be:

namespace('dk.ourclient.supernavigator.controller');

using(dk.ourclient.supernavigator).run(function(sn) {
var m = sn.model,
c = sn.controller,
v = sn.view;

c.ContactController = function(spec) {
//... m.xxx, v.yy
};

});

Which is what we started using. However I was looking at an alternative way to bring sub-modules or packages into scope. I experimented with several forms; here is one of them.


You can think of the following as a small DSL for importing or using package objects in javascript (note, part of the DSL is the JavaScript with statement). It uses a form: (where 'obj' is a package object to be used)

with(f(obj)) {
//code
}

By introducing an intermediate function 'f' and using 'f(obj)' instead of 'obj' itself, we can avoid some of the issues with 'with'.

Question: Does the following code make sense: (with an appropriate definition of the 'scope' function, this is valid working JS code!)

with (scope({ sn : dk.ourclient.supernavigator,
u : com.trifork.utils})) {


with(sn) include()(model,view)
with(u) include()(Format)

run(function(mod,view,fm){
//do stuff
});
}

What does it do? Wait and think before you read on...

I will post an update with code that makes this work later. Hope this is good fun to you, but note that in our project we used the simpler form mentioned previously:

using(dk.ourclient.supernavigator).run(function(sn) {
var m = sn.model,
c = sn.controller,
v = sn.view;

c.ContactController = function(spec) {
//... m.xxx, v.yy
};

});

and I'm sure that Crockford would prefer this too ;-).

/Karl

Saturday, April 19, 2008

HTML-free Web-applications with ExtJS [Designing client/server web-apps, Part I, Section III]

Recap

This article is Part I, Section III of a series discussing the development of client/server web-applications where the client is written in JavaScript and running in a browser. The first article discusses the use of namespacing in large JavaScript applications; it can be found here. The second article gives a high-level overview of our design, and introduces the model part of Model-View-Controller.

This third section of Part I discusses the View in MVC, introducing the concept of HTML-free views in web-applications.

Below is a sample image of the GUI for our client application. It is no so much the application that it interestering, but rather it's design and implementation.

TriBook - a simple room-booking client application
TriBook app 1
Click for large image


The view package object
The package object com.trifork.tribook.view contains all the objects and constructor functions related to the graphical user interface of the client. Particularly, it contains a special singleton object, View, which is an observable object, observed by the Controller; view objects also observe the model, reacting to and reflecting changes.

Apart for the singleton View, the package also contains constructor functions for the various components that exist in the client GUI. In our example room-booking application, TriBook, we have a few such components:

  • com.trifork.tribook.view.RoomForm
    a form-component for entering query data about available rooms

  • com.trifork.tribook.view.RoomReserveView a list component that shows a list of rooms to reserve at certain times

  • com.trifork.tribook.view.RoomView a list component showing the list of available rooms that match the current query in the RoomFoom component.


The View object composes the view using these three components. For example, View contains this code:

namespace("com.trifork.tribook.view");
using(com.trifork.tribook.view).run(function(v) {

v.View = (function() {//singleton module pattern
var view = new Ext.util.Observable(),
events = ['addreservation','removereservation','query','reserve'];

Ext.each(events,function(e){view.addEvents(e);});

return Ext.apply(view, {
init : function() {

Ext.each(['search','book','result'], function(id){
Ext.fly(id).boxWrap();
});//make a nice graphical box on dom el

var roomform = v.RoomForm();
roomform.render('search-inner');

var roomview = v.RoomView();
roomview.render('result-inner');

var roomreserve = v.RoomReserveView();
roomreserve.render('book-inner');

}//some details omitted here
});
})();
});

The code constructs the custom components and tell them to render themselves to various dom elements, e.g., 'search-inner'.

The other important role of View is to define a collection of 'logical' or 'application' or 'domain' events, which the controller (and other view components) may react to. The application events in our room booking app are defined in the events array, e.g., 'query' fires when the user changes the current query in the RoomForm, representing the action of searching for available rooms in a certain time period. 'addreservation' adds a room and a period to the queue of rooms to be reserved (represented as a com.trifork.tribook.model.Reservation object). 'reserve' represents the event that the user wants to actually commit to reserving the rooms in the queue of reservations.

The View object itself doesn't actually contain the code that fires the application events; this code is in the individual view components. E.g., RoomForm fires the 'query' event on View in response to the user changing the form field values (if they validate).

Another way of thinking of this is in terms of event bubbling. Just as DOM events bubble up the dom tree, one can think of the application event 'query' bubbling from the RoomForm object to its parent, the View object. In this way, interested listerners can listen centrally on View and doesn't have to be aware of the structure (i.e. the individual components) of the GUI.

Regarding the use of machine code... (HTML)
The client UI is written without using HTML.

Actually that last statement is not true... However, using ExtJS with say YUI as a base, one has a multitude of high-quality, easily composable and configurable GUI components that are much more high-level than the ubiquitous text markup language. In our view markup is used in two ways: for highly specialized view components and for representing page structure at a high-level. For the latter, the HTML (declaratively) describes the logical placement of three components at the same level: a form, a component for showing a list of rooms, and a component for showing a list of reservations. That is it. The divs are transformed into specialized components using JavaScript. For the second point (highly customized components) we still leverage JavaScript (specifically ExtJS components, XTemplate and DataView).


First let us take a look at a form for entering room search criteria. It's a pretty standard web application form except that it is built entirely in JavaScript. The components are so standard that we just need to compose the fields and specify validation and event handling; no HTML or CSS involved. Here's a sample image:

TriBook - search form with input assistance and validation
TriBook app 1

TriBook app 1


Lets look at some code. One interesting thing to notice in the code below is that although we are writing UI code in JavaScript, the ExtJS framework allows for a highly declarative specification of UI components using configuration object literals (the *Cfg variables below).


namespace("com.trifork.tribook.view");

using(com.trifork.tribook.view).run(function(view){

var model = com.trifork.tribook.model,
ctrl = com.trifork.tribook.controller;
//utility fields and functions defined below
var dateField,fromField,untilField,minField, getCurrentPeriod, filter;

view.RoomForm = function() {
var dateCfg = {
id: 'roomform.date',
xtype:'datefield',
fieldLabel: 'Date',
format: 'd/m/y',
name: 'date',
listeners: {
'change': filter,
'select': filter
}
},
fromCfg = {
id: 'roomform.from',
xtype:'timefield',
fieldLabel: 'Free from',
name: 'time',
format: 'H:i',
increment: 30,
minValue: '09:00',
maxValue: '17:00',
listeners: {
'change': filter,
'select': filter
}
},
untilCfg = { ... },
minCfg = {
id: 'roomform.min',
fieldLabel: 'Min. size',
name: 'size',
validator: function(v) {
if (isNaN(Number(v))) {
return 'Please enter the least number of people that must be supported by the room.';
}
return true;
},
listeners: {
'change': filter
}
};


var form = new Ext.FormPanel({
labelWidth: 75, // label settings here cascade unless overridden
frame:false,
bodyStyle:'padding:5px 5px 0',
width: 310,
defaults: {width: 200},
defaultType: 'textfield',
items: [dateCfg , fromCfg, untilCfg, minCfg],
listeners: {
'render': function(){
dateField = Ext.getCmp('roomform.date');
fromField = Ext.getCmp('roomform.from');
untilField = Ext.getCmp('roomform.until');
minField = Ext.getCmp('roomform.min');
}
}
});

model.Model.rooms.get().on('load',filter);

return form;
};
//detail omitted
});


The filter function that is called when ever the form changes will validate the form; if valid, an event 'query' is fired signaling that the user has queried for available rooms. Notice that the 'query' event carries a parameter, a domain object called a RoomQuery that captures the essence of the query.

...
function filter() {
var p = getCurrentPeriod(),
v = +minField.getValue();

if (p === null || isNaN(v)) {//Not valid
return;
}

view.View.fireEvent('query', new model.RoomQuery({
start_at: p.start,
end_at: p.end,
min_size: v
}));
}
...


The main points...

  • Events and event bubbling. Our application is event driven. Just like dom events bubble up the dom tree and listernes can listen at different levels, our application event bubble up the component tree, e.g., from the RoomForm to the View object. This principle is useful for decoupling for two reasons: (1) observers can attach listerners at different levels of abstraction, e.g. other view objects which may know about the view structure may listen directly on a view component, while listeners in the controller package object may listen directly on the View object, not caring which concrete UI component is the source of the event. (2) individual UI components can focus on mapping dom events to application events with domain concept parameters; they need not be concerned with how those application events are handled.

  • HTML-free views. Except for highly customized components, the view is HTML free. This lets us work at a much higher level of abstraction, i.e., configuring and composing components rather than creating markup tags, and manipulating the dom tree.

  • ExtJS (once again). In version 2 of Ext, components can be specified mostly in a declarative manner which is much more succinct and less error prone. Components are highly customizable and extensible. Even when low-level specialized components are needed ExtJS has support. The brilliant function Ext.DataView combined with Ext.XTemplate provides a powerful tool for presenting lists with tailored HTML; the lists are neatly abstracted with the Ext.data.Store function. You must really check out that trinity!

Saturday, March 8, 2008

Client/Server Web-apps -- the model (Part I, Section II)

This article is Part I, Section II of a series discussing the development of client/server web-applications where the client is written in JavaScript and running in a browser. The first article discusses the use of namespacing in large JavaScript applications; it can be found here.

The next couple of articles will look at one way of using the Model-View-Controller (MVC) design pattern when structuring the client. In doing so, we will touch upon other topics: Crockford's singleton and module patterns, inheritance and the observer/observable design pattern. This article gives a highlevel view of the architecture and presents the Model-part of MVC.

Introduction.

In our webapp, the model-view-controller pattern is used in a manner close to MVC in non-web applications, e.g. Swing applications, which is quite different from the common MVC pattern for web-apps (e.g., as done in JSP Model 1 and Model 2 architectures, Rails, JSF etc.). For example, in the JSP Model2 architecture, the controller is a Servlet that receives a HTTP request, possibly manipulates the model (implemented as a collection of Java Beans), and finally dispatches to the view (implemented as a collection of JSP templates that consult model objects when rendering HTML).

Our server doesn't deliver any HTML. The server's responsibility is simply to implement a HTTP-based RESTful API for accessing resources (in fact, the server application itself is not structured by MVC, since it has no view in the traditional sense). The JavaScript client is decoupled from the server application and interacts with it only through the exchange of JSON data. Hence, our web-application is much more like a traditional distributed client/server application than a regular HTML-centric web-application. In fact, also our client application will be HTML-free! (I kind of like the name 'HTML-free' web-applications for this type of web-app). This sounds impossible, and actually it only mostly true ;-). However, using the JavaScript framework ExtJS, we are able to only use HTML for the 'lowest-level' custom functionality: all other GUI elements are composed of (JavaScript-) customized Ext Components and Containers. This let's us develop the view largely without thinking about HTML or ugly HTML-templates (of course Ext uses HTML internally).

So, it is the client that is structured by MVC. In fact, MVC can be implemented quite elegantly in JavaScript (I wonder if this is connected to the fact that MVC was originally developed for GUI applications written in Smalltalk, a language that in some ways is close to JavaScript).

We will use the singleton pattern for the controller, model and view, and so there are no constructor functions for these objects. Each of these are accessed as:

com.trifork.tribook.controller.Controller
com.trifork.tribook.model.Model
com.trifork.tribook.view.View


Their responsibilities are as follows:

  • Model represents the state of the application in terms of concepts from the application domain (Rooms and Reservations in our example). It is an observable object, which fires events when state changes.

  • View sets up all the GUI elements. It is also an observable object. The events fired by the view are not low-level events like DOM events; instead, they are logical events which are triggered by such low-level events, e.g., clicking on a button. An example logical event could be 'room reservation'.

  • Controller initializes model and view. It also listens on model and view events. For example, a controller component will be responsible for handling the logical 'room reservation' event fired by the view. Controller also manipulates the model (thus triggering more events) in response to, e.g., the result of Ajax requests.



An advantage of the event-driven programming model is that there is a loose coupling between the source of events and code that responds to such events. Furthermore, most of the time there can be several handlers for each event, and such handlers need not be aware of each other.

Recall that our example application, TriBook, is a simple room-booking application for reserving meeting rooms at Trifork. In the following we will look at the structure of the model-part of our TriBook application. We will be using the JavaScript framework ExtJS (the strongest JavaScript framework I know of) when defining the Model and associated domain concepts; also, we will use the namespace and using functions from the previous article.

The Model
The object: com.trifork.tribook.model is a so-called package object; it does not contain any logic, and serves only as a container for all objects and functions related to the model. In our TriBook application, this includes: Model (the model-object mentioned above), Room (a constructor function for the domain concept of a Room), Reservation (constructor for Reservation objects) and RoomQuery (constructor for objects representing a query for available rooms).

When defining domain constructor functions, we will use ExtJS, specifically: Ext.data.Record. This object has a method, called create, which is a higher-order function that returns a constructor function for a 'record' object, which are ideal for domain modeling for several reasons (as we shall see). This should make much more sense, when seeing the code:

namespace("com.trifork.tribook.model");
using(com.trifork.tribook.model).run(function(m){

var format = 'd/m/Y-H:i';
m.Reservation = Ext.data.Record.create([
{name: 'start_at', type:'date', dateFormat:format},
{name: 'end_at', type:'date', dateFormat:format},
//belongs_to room
{name: 'room'}//no 'type' means arbitrary object
]);
});

This code defines the Reservation domain concept: a reservation has a start and end time and refers to a Room object (the room being reserved). The 'dateFormat' property tells Ext how to parse a string to a Date object.

Since Ext.data.Record.create returns a constructor function, we can add domain logic to our domain objects by augmenting their prototypes. Below, we illustrate this with the Room domain concept which has a method 'isFreeFor' that returns true iff this room is available to the input RoomQuery object:

namespace("com.trifork.tribook.model");
using(com.trifork.tribook.model).run(function(m){
var rsvReader = new Ext.data.JsonReader({
root: "reservations"
}, m.Reservation);//converts JSON objects to Reservation objects

m.Room = Ext.data.Record.create([
{name: 'name', type:'string'},
{name: 'room_code', type:'string'},
{name: 'description', type:'string'},
{name: 'max_size', type:'int'},
{name: 'picture_url', type:'string'},
{name: 'map_url', type:'string'},

//Room has_many :reservations
{
name: 'reservations',

//this tells Ext how to convert a JSON array to
//an array of m.Reservation objects
//room is a reference back to the room object itself
convert: function(rsvs,room) {
Ext.each(rsvs, function(r){
Ext.apply(r,{room:room});//adds a room property to r
});
return rsvReader.readRecords({'reservations':rsvs}).records;
}
}
]);

//is this room free for input room query object?
m.Room.prototype.isFreeFor = function(query) {
return (query.get('min_size') <= this.get('max_size')) &&
! this.get('reservations').some(function reserved(period) {
//... details omitted
});
};
});

I think it is noteworthy how succinctly we can define domain concepts using Ext, e.g., {name: 'name', type:'string'} declaratively specifies that rooms have a 'name' property of type 'string'. Further, using Ext.data.Record objects as our domain objects we can leverage other Ext functions in several ways: for example Ext.data.JsonReader or Ext.data.XmlReader automatically converts JSON or XML data representations of domain objects to actual domain object instances. Furthermore, the Ext.data.Store abstraction gives us a client-local cache of domain objects; something we will be using in the Model object.

The observable/observer pattern. It should come as no surprise that we are also leveraging ExtJS in our use of the observable pattern: the com.trifork.tribook.model.Model objects is an instance of the type Ext.util.Observable. This gives us the ability to add named events which can be fired and all listeners notified. For example, we have the following (note that Ext.apply(A,B) copies all the properties of object B to object A):

namespace("com.trifork.tribook.model");
using(com.trifork.tribook.model).run(function(m){
//details omitted here...

m.Model = (function() {//inline
var model = new Ext.util.Observable();
model.addEvents('beforequery','query','beforerooms','rooms');

return Ext.apply(model, {
init: function(conf) {
this.rooms.set(conf.rooms);
},
//attr_accessor defined below
rooms: attr_accessor('rooms'),
query: attr_accessor('query'),
pendingReservations: attr_accessor({
name:'pendingReservations',
setter: false
})
});
})();
//details omitted here...
...

Ignore 'attr_accessor' for now, it simply creates a property on the Model object (if you know rails you can probably guess what it does) - we will get back to this later. Model is an observable object with events: 'beforerooms', 'rooms', 'beforequery' and 'query'. The client application always has a current query which represents the period in time that the user is presently interested in (represented as a form in the view). The controller makes sure that the query property of the model is updated when the user changes the form values, and hence the 'query' event is fired with the updated value as a parameter. Other view components, in turn, listen on this model property and react to these changes, which removes dependencies from the view and gives a looser coupling.

Using Ext, adding an event listener can be done as follows: m.Model.on('query', function(q){...});. When the 'query' event is fired on the model, the supplied function is called, binding an optional event parameter to q. Similarly, firing an event is simple: m.Model.fireEvent('query', new m.RoomQuery(...));. When an event is fired, all listeners are invoked in turn.

The full model source is:

/*extern com, Tri, Ext*/
namespace("com.trifork.tribook.model");
using(com.trifork.tribook.model).run(function(m){
var State = {
rooms: null,
query: null,
pendingReservations: new Ext.data.Store()
};

m.Model = (function() {//inline
var model = new Ext.util.Observable();
model.addEvents('beforequery','query','beforerooms','rooms');

return Ext.apply(model, {
init: function(conf) {
this.rooms.set(conf.rooms);
},
//attr_accessor defined below
rooms: attr_accessor('rooms'),
query: attr_accessor('query'),
pendingReservations: attr_accessor({
name:'pendingReservations',
setter: false
})
});
})();

//create an attribute accessor pair.
function attr_accessor(spec){
spec = typeof spec === 'string' ? {name: spec, setter:true} : spec;
var name = spec.name,
before = 'before'+name,
res = {
get: function(){
return State[name];
}
};
if (spec.setter) {
res.set = function(val){
var old_val = State[name];
if (m.Model.fireEvent(before,val,old_val) !== false){
State[name] = val;
m.Model.fireEvent(name,val,old_val);
}
};
}
return res;
}
});

Conclusion
At the end of this writing, I somehow feel that I've not completely expressed my points as clearly as I would have liked -- this paragraph is an attempt to remedy this. Since I am unsure how to re-write this posting more concisely, I'll just try and emphasize my main messages:

  • Our 'web-app' should be thought of as a regular distributed client/server app. The server uses RESTful HTTP, and is HTML free; it's primary format for resource representation is application/json. (All this is a topic of a later posting). The client is written JavaScript and is (almost) HTML free. The client is structured after MVC. Client and server constitute a HTML-free webapplication!

  • The MVC design is event based; this simplifies components and reduces coupling. The view manages the GUI and converts user actions to logical application events. Controller handles application events. Model represents the state of the (client) application; it fires events when state changes.

  • The package object com.trifork.tribook.model contains domain concepts (e.g. Room); it also contains the actual Model object. The state of Model is represented via the domain concepts.

  • I highly recommend ExtJS in developing this type of client application. Ext is extremely useful in M, V and C; for this posting we focused on M, where the Ext features support for:

    • concise definition of domain concepts using Ext.data.Record

    • client caches (collections) of domain objects, asynchronously linked to a server backend, i.e., Ext.data.Store, Ext.data.HttpProxy

    • observer/observable design pattern: Ext.util.Observable

    • XML and JSON parsing and mapping to domain concepts (Ext.data.JsonReader, Ext.data.XmlReader)

    • and of course Ext itself is highly extensible and event based