Minimal Tutorial
Minimal Tutorial
iii
JS Front-End Web
Apps for Beginners
iv
List of Figures
2.1. The built-in JavaScript classes Object and Function. .................................................... 22
3.1. The object type Book. ....................................................................................................... 26
3.2. The minimal app's start page. ............................................................................................. 27
3.3. The object type Movie. ..................................................................................................... 39
v
List of Tables
2.1. An example of an entity table representing a collection of books ........................................... 16
2.2. Required and desirable features of JS code patterns for classes ............................................. 19
2.3. An entity table representing a collection of books ................................................................ 24
3.1. A sample population for the object type Book .................................................................... 26
3.2. An entity table representing a collection of books ................................................................ 28
3.3. A collection of book objects represented as a table .............................................................. 29
3.4. Sample data ....................................................................................................................... 40
vi
Foreword
This tutorial is Part 1 of our series of six tutorials [[Link] about
model-based development of front-end web applications with plain JavaScript. It shows how to build
such an app with minimal effort, not using any (third-party) framework or library. While libraries and
frameworks may help to increase productivity, they also create black-box dependencies and overhead,
and they are not good for learning how to do it yourself.
This tutorial provides theoretically underpinned and example-based learning materials and supports
learning by doing it yourself.
A front-end web app can be provided by any web server, but it is executed on the user's computer device
(smartphone, tablet or notebook), and not on the remote web server. Typically, but not necessarily, a
front-end web app is a single-user application, which is not shared with other users.
The minimal version of a JavaScript front-end data management application discussed in this tutorial
only includes a minimum of the overall functionality required for a complete app. It takes care of only
one object type ("books") and supports the four standard data management operations (Create/Read/
Update/Delete), but it needs to be enhanced by styling the user interface with CSS rules, and by adding
further important parts of the app's overall functionality. The other parts of the tutorial are:
• Part 4 [[Link]
Managing unidirectional associations, such as the associations between books and publishers,
assigning a publisher to a book, and between books and authors, assigning authors to a book.
• Part 5 [[Link]
Managing bidirectional associations, such as the associations between books and publishers and
between books and authors, not only assigning authors and a publisher to a book, but also the other
way around, assigning books to authors and to publishers.
vii
Chapter 1. A Quick Tour of the
Foundations of Web Apps
If you are already familiar with HTML, XML and JavaScript, you may skip this chapter and immediately
start developing a minimal web application by going to the next chapter.
• web server programs, acting as HTTP servers, as well as web 'user agents' (such as browsers), acting
as HTTP clients.
Later, further important technology components have been added to this set of basic web technologies:
• the Extensible Markup Language (XML), as the basis of web formats (like SVG and RDF/XML),
in 1998,
• the Resource Description Framework (RDF) for knowledge representation on the Web in 2004.
• document formats, such as XHTML5, the Scalable Vector Graphics (SVG) format or the DocBook
format,
• data interchange file formats, such as the Mathematical Markup Language (MathML) or the
Universal Business Language (UBL),
• message formats, such as the web service message format SOAP [[Link]
part0/]
1
A Quick Tour of the
Foundations of Web Apps
Unicode includes legacy character sets like ASCII and ISO-8859-1 (Latin-1) as subsets.
The default encoding of an XML document is UTF-8, which uses only a single byte for ASCII characters,
but three bytes for less common characters.
Almost all Unicode characters are legal in a well-formed XML document. Illegal characters are the
control characters with code 0 through 31, except for the carriage return, line feed and tab. It is
therefore dangerous to copy text from another (non-XML) text to an XML document (often, the form
feed character creates a problem).
XML namespaces are identified with the help of a namespace URI, such as the SVG namespace URI
"[Link] which is associated with a namespace prefix, such as svg. Such a
namespace represents a collection of names, both for elements and attributes, and allows namespace-
qualified names of the form prefix:name, such as svg:circle as a namespace-qualified name for
SVG circle elements.
A default namespace is declared in the start tag of an element in the following way:
<html xmlns="[Link]
This example shows the start tag of the HTML root element, in which the XHTML namespace is declared
as the default namespace.
The following example shows a namespace declaration for an svg element embedded in an HTML
document:
<html xmlns="[Link]
<head>
...
</head>
<body>
<figure>
<figcaption>Figure 1: A blue circle</figcaption>
<svg:svg xmlns:svg="[Link]
<svg:circle cx="100" cy="100" r="50" fill="blue"/>
</svg:svg>
</figure>
</body>
</html>
2
A Quick Tour of the
Foundations of Web Apps
2. Each element has a start tag and an end tag; however, empty elements can be closed as <phone/
> instead of <phone></phone>.
4. Attribute names are unique within the scope of an element, e.g. the following code is not correct:
<attachment file="[Link]" file="[Link]"/>
An XML document is called valid against a particular grammar (such as a DTD or an XML Schema), if
1. it is well-formed,
• 2014: (X)HTML5 in cooperation (and competition) with the WHAT working group [http://
[Link]/wiki/WHATWG] supported by browser vendors.
As the inventor of the Web, Tim Berners-Lee developed a first version of HTML [http://
[Link]/History/19921103-hypertext/hypertext/WWW/MarkUp/[Link]] in 1990. In the
following years, HTML has been used and gradually extended by a growing community of early
WWW adopters. This evolution of HTML, which has led to a messy set of elements and attributes
(called "tag soup"), has been mainly controlled by browser vendors and their competition with
each other. The development of XHTML in 2000 was an attempt by the W3C to clean up this mess,
but it neglected to advance HTML's functionality towards a richer user interface, which was the
focus of the WHAT working group [[Link] led by Ian Hickson
[[Link] who can be considered as the mastermind and main
author of HTML 5 and many of its accompanying JavaScript APIs that made HTML fit for mobile
apps.
HTML was originally designed as a structure description language, and not as a presentation description
language. But HTML4 has a lot of purely presentational elements such as font. XHTML has been
taking HTML back to its roots, dropping presentational elements and defining a simple and clear syntax,
in support of the goals of
• device independence,
• accessibility, and
• usability.
3
A Quick Tour of the
Foundations of Web Apps
because we prefer the clear syntax of XML documents over the liberal and confusing HTML4-style
syntax that is also allowed by HTML5.
The following simple example shows the basic code template to be used for any HTML document:
<!DOCTYPE html>
<html xmlns="[Link] xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>XHTML5 Template Example</title>
</head>
<body>
<h1>XHTML5 Template Example</h1>
<section><h1>First Section Title</h1>
...
</section>
</body>
</html>
Notice that in line 1, the HTML5 document type is declared, such that browsers are instructed to use the
HTML5 document object model (DOM). In the html start tag in line 2, using the default namespace
declaration attribute xmlns, the XHTML namespace URI [Link] is
declared as the default namespace for making sure that browsers, and other tools, understand that all
non-qualified element names like html, head, body, etc. are from the XHTML namespace.
Also in the html start tag, we set the (default) language for the text content of all elements (here to "en"
standing for English) using both the xml:lang attribute and the HTML lang attribute. This attribute
duplication is a small price to pay for having a hybrid document that can be processed both by HTML
and by XML tools.
Finally, in line 4, using an (empty) meta element with a charset attribute, we set the HTML
document's character encoding to UTF-8, which is also the default for XML documents.
Users complete a form by entering text into input fields and by selecting items from choice controls.
A completed form is submitted with the help of a submit button. When a user submits a form, it is
normally sent to a web server either with the HTTP GET method or with the HTTP POST method. The
standard encoding for the submission is called URL-encoded. It is represented by the Internet media
type application/x-www-form-urlencoded. In this encoding, spaces become plus signs, and
any other reserved characters become encoded as a percent sign and hexadecimal digits, as defined in
RFC 1738.
Each control has both an initial value and a current value, both of which are strings. The initial value
is specified with the control element's value attribute, except for the initial value of a textarea
element, which is given by its initial contents. The control's current value is first set to the initial value.
4
A Quick Tour of the
Foundations of Web Apps
Thereafter, the control's current value may be modified through user interaction or scripts. When a form
is submitted for processing, some controls have their name paired with their current value and these
pairs are submitted with the form.
Labels are associated with a control by including the control as a child element within a label element
("implicit labels"), or by giving the control an id value and referencing this ID in the for attribute of the
label element ("explicit labels"). It seems that implicit labels are (in 2015) still not widely supported
by CSS libraries and assistive technologies. Therefore, explicit labels may be preferable, despite the fact
that they imply quite some overhead by requiring a reference/identifier pair for every labeled HTML
form field.
In the simple user interfaces of our "Getting Started" applications, we only need four types of form
controls:
1. single line input fields created with an <input name="..." /> element,
2. single line output fields created with an <output name="..." /> element,
4. dropdown selection lists created with a select element of the following form:
<select name="...">
<option value="value1"> option1 </option>
<option value="value2"> option2 </option>
...
</select>
An example of an HTML form with implicit labels for creating such a user interface is
<form id="Book">
<p><label>ISBN: <output name="isbn" /></label></p>
<p><label>Title: <input name="title" /></label></p>
<p><label>Year: <input name="year" /></label></p>
<p><button type="button">Save</button></p>
</form>
In general, an attribute of a model class can always be represented in the user interface by a plain input
control (with the default setting type="text"), no matter which datatype has been defined as the
range of the attribute in the model class. However, in special cases, other types of input controls (for
instance, type="date"), or other controls, may be used. For instance, if the attribute's range is an
enumeration, a select control or, if the number of possible choices is small enough (say, less than
8), a radio button group can be used.
5
A Quick Tour of the
Foundations of Web Apps
and which animations. Normally, these settings are made in a separate CSS file that is associated with
an HTML file via a special link element in the HTML's head.
The basic element of a CSS layout [[Link] is a rectangle, also called "box", with an
inner content area, an optional border, an optional padding (between content and border) and an optional
margin around the border. This structure is defined by the CSS box model [[Link]
wiki/guides/the_css_layout_model].
We will not go deeper into CSS in this tutorial, since our focus here is on the logic and functionality
of an app, and not so much on its beauty.
JavaScript is a dynamic functional object-oriented programming language that can be used for
6
A Quick Tour of the
Foundations of Web Apps
3. Implementing a front-end web application with local or remote data storage, as described in the book
Building Front-End Web Apps with Plain JavaScript [[Link]
Book].
4. Implementing a front-end component for a distributed web application with remote data storage
managed by a back-end component, which is a server-side program that is traditionally written in a
server-side language such as PHP, Java or C#, but can nowadays also be written in JavaScript with
NodeJS.
5. Implementing a complete distributed web application where both the front-end and the back-end
components are JavaScript programs.
The version of JavaScript that is currently supported by web browsers is called "ECMAScript 5.1", or
simply "ES5", but the next two versions, called "ES6" and "ES7" (or "ES 2015" and "ES 2016", as new
versions are planned on a yearly basis), with lots of added functionality and improved syntaxes, are
around the corner (and already partially supported by current browsers and back-end JS environments).
However, objects can also be created without instantiating a class, in which case they are untyped, and
properties as well as methods can be defined for specific objects independently of any class definition. At
run time, properties and methods can be added to, or removed from, any object and class. This dynamism
of JavaScript allows powerful forms of meta-programming, such as defining your own concepts of
classes and enumerations (and other special datatypes).
7
A Quick Tour of the
Foundations of Web Apps
1. How browsers interact with screen readers, and where ARIA fits in the mix [[Link]
by Bryan Garaventa
8
Chapter 2. More on JavaScript
1. JavaScript Basics
In this summary we try to take all important points of the classical JavaScript summary
[[Link] by Douglas Crockford [[Link] into
consideration.
There are five reference types: Object, Array, Function, Date and RegExp. Arrays, functions,
dates and regular expressions are special types of objects, but, conceptually, dates and regular
expressions are primitive data values, and happen to be implemented in the form of wrapper objects.
The types of variables, array elements, function parameters and return values are not declared and are
normally not checked by JavaScript engines. Type conversion (casting) is performed automatically.
• an object reference: either referencing an ordinary object, or an array, function, date, or regular
expression;
• the special data value null, which is typically used as a default value for initializing an object
variable;
• the special data value undefined, which is the implicit initial value of all variables that have been
declared, but not initialized.
A string is a sequence of Unicode characters. String literals, like "Hello world!", 'A3F0', or the empty
string "", are enclosed in single or double quotes. Two string expressions can be concatenated with the
+ operator, and checked for equality with the triple equality operator:
if (firstName + lastName === "James Bond") ...
The number of characters of a string can be obtained by applying the length attribute to a string:
[Link]("Hello world!".length); // 12
All numeric data values are represented in 64-bit floating point format with an optional exponent (like
in the numeric data literal 3.1e10). There is no explicit type distinction between integers and floating
point numbers. If a numeric expression cannot be evaluated to a number, its value is set to NaN ("not a
number"), which can be tested with the buil-in predicate isNaN(expr).
9
More on JavaScript
decimal number can be converted to this number with parseFloat. For converting a number n to a
string, the best method is using String(n).
There are two pre-defined Boolean data literals, true and false, and the Boolean operator symbols
are the exclamation mark ! for NOT, the double ampersand && for AND, and the double bar || for
OR. When a non-Boolean value is used in a condition, or as an operand of a Boolean expression, it
is implicitly converted into a Boolean value according to the following rules. The empty string, the
(numerical) data literal 0, as well as undefined and null, are mapped to false, and all other values
are mapped to true. This conversion can be performed explicitly with the help of the double negation
operation, like in the equality test !!undefined === false, which evaluates to true.
In addition to strings, numbers and Boolean values, also calendar dates and times are important types of
primitive data values, although they are not implemented as primitive values, but in the form of wrapper
objects instantiating Date. Notice that Date objects do, in fact, not really represent dates, but rather
date-time instants represented internally as the number of milliseconds since 1 January, 1970 UTC. For
converting the internal value of a Date object to a human-readable string, we have several options.
The two most important options are using either the standard format of ISO date/time strings of the
form "2015-01-27", or localized formats of date/time strings like "27.1.2015" (for simplicity, we have
omitted the time part of the date/time strings in these examples). When x instanceof Date, then
[Link]() provides the ISO date/time string, and [Link]() provides
the localized date/time string. Given any date string ds, ISO or localized, new Date(ds) creates a
corresponding date object.
For testing the equality (or inequality) of two primitive data vales, always use the triple equality symbol
=== (and !==) instead of the double equality symbol == (and !=). Otherwise, for instance, the number
2 would be the same as the string "2", since the condition (2 == "2") evaluates to true in JavaScript.
Assigning an empty array literal, as in var a = [] is the same as, but more concise than and therefore
preferred to, invoking the Array() constructor without arguments, as in var a = new Array().
Assigning an empty object literal, as in var o = {} is the same as, but more concise than
and therefore preferred to, invoking the Object() constructor without arguments, as in var o
= new Object(). Notice, however, that an empty object literal {} is not really an empty
object, as it contains property slots and method slots inherited from [Link] [https://
[Link]/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype]. So, a
truly empty object (without any slots) has to be created with null as prototype, like in var
emptyObject = [Link](null).
10
More on JavaScript
11
More on JavaScript
function foo() {
for (var i=0; i < 10; i++) {
... // do something with i
}
}
Instead, and this is exactly how JavaScript is interpreting this code (by means of "hoisting" variable
declarations), we should write:
function foo() {
var i=0;
for (i=0; i < 10; i++) {
... // do something with i
}
}
All variables should be declared at the beginning of a function. Only in the next version of JavaScript,
ES6, block scope will be supported by means of a new form of variable declaration with the keyword
let.
We can turn strict mode on by typing the following statement as the first line in a JavaScript file or
inside a <script> element:
'use strict';
It is generally recommended that you use strict mode, except your code depends on libraries that are
incompatible with strict mode.
A JS object is essentially a set of name-value-pairs, also called slots, where names can be property
names, function names or keys of a map. Objects can be created in an ad-hoc manner, using JavaScript's
object literal notation (JSON), without instantiating a class:
var person1 = { lastName:"Smith", firstName:"Tom"};
var o1 = [Link]( null); // an empty object with no slots
1. a data-valued property, in which case the value is a data value or, more generally, a data-valued
expression;
or
12
More on JavaScript
2. an object-valued property, in which case the value is an object reference or, more generally, an
object expression.
The name in a method slot denotes a JS function (better called method), and its value is a JS function
definition expression.
JS objects can be used in many different ways for different purposes. Here are five different use cases
for, or possible meanings of, JS objects:
2. A map (also called 'associative array', 'dictionary', 'hash map' or 'hash table' in other languages)
supports look-ups of values based on keys like, for instance,
var numeral2number = {"one":"1", "two":"2", "three":"3"}
which associates the value "1" with the key "one", "2" with "two", etc. A key need not be a valid
JavaScript identifier, but can be any kind of string (e.g. it may contain blank spaces).
3. An untyped object does not instantiate a class. It may have property slots and method slots like, for
instance,
var person1 = {
lastName: "Smith",
firstName: "Tom",
getFullName: function () {
return [Link] +" "+ [Link];
}
};
Within the body of a method slot of an object, the special variable this refers to the object.
4. A namespace may be defined in the form of an untyped object referenced by a global object
variable, the name of which represents a namespace prefix. For instance, the following object
variable provides the main namespace of an application based on the Model-View-Controller (MVC)
architecture paradigm where we have three subnamespaces corresponding to the three parts of an
MVC application:
var myApp = { model:{}, view:{}, ctrl:{} };
5. A typed object instantiates a class that is defined either by a JavaScript constructor function or by a
factory object. See Section 1.9, “Defining and using classes”
13
More on JavaScript
without saying 'JS array' creates a terminological ambiguity. But for simplicity, we will sometimes just
say 'array' instead of 'JS array'.
Because they are array lists, JS arrays can grow dynamically: it is possible to use indexes that are greater
than the length of the array. For instance, after the array variable initialization above, the array held by
the variable a has the length 3, but still we can assign a fifth array element like in
a[4] = 7;
The contents of an array a are processed with the help of a standard for loop with a counter variable
counting from the first array index 0 to the last array index, which is [Link]-1:
for (i=0; i < [Link]; i++) { ...}
Since arrays are special types of objects, we sometimes need a method for finding out if a variable
represents an array. We can test, if a variable a represents an array by applying the predefined datatype
predicate isArray as in [Link]( a).
For adding a new element to an array, we append it to the array using the push operation as in:
[Link]( newElement);
For deleting an element at position i from an array a, we use the pre-defined array method splice
as in:
[Link]( i, 1);
For searching a value v in an array a, we can use the pre-defined array method indexOf, which returns
the position, if found, or -1, otherwise, as in:
if ([Link](v) > -1) ...
For looping over an array a, we have two options: either use a for loop, or the array looping method
forEach. In any case, we can use a for loop:
var i=0;
for (i=0; i < [Link]; i++) {
[Link]( a[i]);
}
If performance doesn't matter, that is, if a is sufficiently small (say, it does not contain more than a few
hundred elements), we can use the array looping method forEach, as in the following example, where
the parameter elem iteratively assumes each element of the array a as its value:
[Link]( function (elem) {
[Link]( elem);
})
For cloning an array a, we can use the array function slice in the following way:
var clone = [Link](0);
1.6. Maps
A map (also called 'hash map' or 'associative array') provides a mapping from keys to their associated
values. The keys of a JS map are string literals that may include blank spaces like in:
var myTranslation = {
14
More on JavaScript
A map is processed with the help of a special loop where we loop over all keys of the map using the
pre-defined function [Link](m), which returns an array of all keys of a map m. For instance,
var i=0, key="", keys=[];
keys = [Link]( myTranslation);
for (i=0; i < [Link]; i++) {
key = keys[i];
alert('The translation of '+ key +' is '+
myTranslation[key]);
}
For adding a new entry to a map, we simply associate the new value with its key as in:
myTranslation["my car"] = "mein Auto";
For deleting an entry from a map, we can use the pre-defined delete operator as in:
delete myTranslation["my boat"];
For searching in a map if it contains an entry for a certain key value, such as for testing if the translation
map contains an entry for "my bike" we can check the following:
if ("my bike" in myTranslation) ...
For looping over a map m, we first convert it to an array of its keys with the help of the predefined
[Link] method, and then we can use either a for loop or the forEach method. The following
example shows how to loop with for:
var i=0, key="", keys=[];
keys = [Link]( m);
for (i=0; i < [Link]; i++) {
key = keys[i];
[Link]( m[key]);
}
Again, if m is sufficiently small, we can use the forEach method, as in the following example:
[Link]( m).forEach( function (key) {
[Link]( m[key]);
})
For cloning a map m, we can use the composition of [Link] and [Link]. We first serialize
m to a string representation with [Link], and then de-serialize the string representation to a map
object with [Link]:
var clone = [Link]( [Link]( m))
Notice that this method works well if the map contains only simple data values or (possibly nested)
arrays/maps containing simple data values. In other cases, e.g. if the map contains Date objects, we
have to write our own clone method.
1. array lists, such as ["one","two","three"], which are special JS objects called 'arrays', but
since they are dynamic, they are rather array lists as defined in the Java programming language.
15
More on JavaScript
3. maps, which are also special JS objects, such as {"one":1, "two":2, "three":3}, as
discussed above,
4. entity tables, like for instance the table shown below, which are special maps where the values are
entity records with a standard ID (or primary key) slot, such that the keys of the map are the standard
IDs of these entity records.
Notice that our distinction between maps, records and entity tables is a purely conceptual
distinction, and not a syntactical one. For a JavaScript engine, both {firstName:"Tom",
lastName:"Smith"} and {"one":1,"two":2,"three":3} are just objects. But
conceptually, {firstName:"Tom", lastName:"Smith"} is a record because firstName and
lastName are intended to denote properties (or fields), while {"one":1,"two":2,"three":3}
is a map because "one" and "two" are not intended to denote properties/fields, but are just arbitrary
string values used as keys for a map.
Making such conceptual distinctions helps in the logical design of a program, and mapping them to
syntactic distinctions, even if they are not interpreted differently, helps to better understand the intended
computational meaning of the code and therefore improves its readability.
Being JS objects implies that JS functions can be stored in variables, passed as arguments to functions,
returned by functions, have properties and can be changed dynamically. Therefore, JS functions are
first-class citizens, and JavaScript can be viewed as a functional programming language.
16
More on JavaScript
Anonymous function expressions are called lambda expressions (or shorter lambdas) in other
programming languages.
that is, it creates both a function with name theNameOfMyMethod and a variable
theNameOfMyMethod referencing this function.
JS functions can have inner functions. The closure mechanism allows a JS function using variables
(except this) from its outer scope, and a function created in a closure remembers the environment in
which it was created. In the following example, there is no need to pass the outer scope variable result
to the inner function via a parameter, as it is readily available:
var sum = function (numbers) {
var result = 0;
[Link]( function (n) {
result = result + n;
});
return result;
};
[Link]( sum([1,2,3,4])); // 10
When a method/function is executed, we can access its arguments within its body by using the built-
in arguments object, which is "array-like" in the sense that it has indexed elements and a length
property, and we can iterate over it with a normal for loop, but since it's not an instance of Array,
the JS array methods (such as the forEach looping method) cannot be applied to it. The arguments
object contains an element for each argument passed to the method. This allows defining a method
without parameters and invoking it with any number of arguments, like so:
var sum = function () {
var result = 0, i=0;
for (i=0; i < [Link]; i++) {
result = result + arguments[i];
}
return result;
};
[Link]( sum(0,1,1,2,3,5,8)); // 20
A method defined on the prototype of a constructor function, which can be invoked on all objects
created with that constructor, such as [Link], where Array represents the
constructor, has to be invoked with an instance of the class as context object referenced by the this
variable (see also the next section on classes). In the following example, the array numbers is the
context object in the invocation of forEach:
17
More on JavaScript
Whenever such a prototype method is to be invoked not with a context object, but with an object as an
ordinary argument, we can do this with the help of the JS function call method that takes an object,
on which the method is invoked, as its first parameter, followed by the parameters of the method to be
invoked. For instance, we can apply the forEach looping method to the array-like object arguments
in the following way:
var sum = function () {
var result = 0;
[Link]( arguments, function (n) {
result = result + n;
});
return result;
};
Whenever a method defined for a prototype is to be invoked without a context object, or when a
method defined in a method slot (in the context) of an object is to be invoked without its context
object, we can bind its this variable to a given object with the help of the JS function bind
method ([Link]). This allows creating a shortcut for invoking a method, as
in var querySel = [Link]( document), which allows to use
querySel instead of [Link].
The option of immediately invoked JS function expressions can be used for obtaining a namespace
mechanism that is superior to using a plain namespace object, since it can be controlled which variables
and methods are globally exposed and which are not. This mechanism is also the basis for JS module
concepts. In the following example, we define a namespace for the model code part of an app, which
exposes some variables and the model classes in the form of constructor functions:
[Link] = function () {
var appName = "My app's name";
var someNonExposedVariable = ...;
function ModelClass1() {...}
function ModelClass2() {...}
function someNonExposedMethod(...) {...}
return {
appName: appName,
ModelClass1: ModelClass1,
ModelClass2: ModelClass2
}
}(); // immediately invoked
This pattern has been proposed in the [Link] article JavaScript best practices [https://
[Link]/wiki/tutorials/javascript_best_practices].
Having a class concept is essential for being able to implement a data model in the form of model classes
in a Model-View-Controller (MVC) architecture. However, classes and their inheritance/extension
18
More on JavaScript
mechanism are over-used in classical OO languages, such as in Java, where all variables and procedures
have to be defined in the context of a class and, consequently, classes are not only used for implementing
object types (or model classes), but also as containers for many other purposes in these languages. This
is not the case in JavaScript where we have the freedom to use classes for implementing object types
only, while keeping method libraries in namespace objects.
Any code pattern for defining classes in JavaScript should satisfy five requirements. First of all, (1) it
should allow to define a class name, a set of (instance-level) properties, preferably with the option to
keep them 'private', a set of (instance-level) methods, and a set of class-level properties and methods. It's
desirable that properties can be defined with a range/type, and with other meta-data, such as constraints.
There should also be two introspection features: (2) an is-instance-of predicate that can be used for
checking if an object is a direct or indirect instance of a class, and (3) an instance-level property for
retrieving the direct type of an object. In addition, it is desirable to have a third introspection feature
for retrieving the direct supertype of a class. And finally, there should be two inheritance mechanisms:
(4) property inheritance and (5) method inheritance. In addition, it is desirable to have support for
multiple inheritance and multiple classifications, for allowing objects to play several roles at the same
time by instantiating several role classes.
There is no explicit class concept in JavaScript. Different code patterns for defining classes in JavaScript
have been proposed and are being used in different frameworks. But they do often not satisfy the five
requirements listed above. The two most important approaches for defining classes are:
1. In the form of a constructor function that achieves method inheritance via the prototype chain and
allows to create new instances of a class with the help of the new operator. This is the classical
approach recommended by Mozilla in their JavaScript Guide [[Link]
docs/Web/JavaScript/Guide/Details_of_the_Object_Model].
2. In the form of a factory object that uses the predefined [Link] method for creating new
instances of a class. In this approach, the prototype chain method inheritance mechanism is replaced
by a copy&append mechanism. Eric Elliott [[Link]
[Link]#fluentstyle_javascript] has argued that factory-based classes are a viable alternative to
constructor-based classes in JavaScript (in fact, he even condemns the use of classical inheritance
with constructor-based classes, throwing out the baby with the bath water).
When building an app, we can use both kinds of classes, depending on the requirements of the app.
Since we often need to define class hierarchies, and not just single classes, we have to make sure,
however, that we don't mix these two alternative approaches within the same class hierarchy. While
the factory-based approach, as exemplified by mODELcLASSjs [[Link]
mODELcLASSjs/[Link]], has many advantages, which are summarized in Table 2.2,
the constructor-based approach enjoys the advantage of higher performance object creation.
Table 2.2. Required and desirable features of JS code patterns for classes
Class feature Constructor-based Factory-based mODELcLASSjs
approach approach [[Link]
[Link]/tech/
mODELcLASSjs/
validation-
[Link]]
Define properties and yes yes yes
methods
is-instance-of predicate yes yes yes
direct type property yes yes yes
19
More on JavaScript
Only in ES6, a user-friendly syntax for constructor-based classes has been introduced. In Step
1.a), a base class Person is defined with two properties, firstName and lastName, as well as
with an (instance-level) method toString and a static (class-level) method checkLastName:
class Person {
constructor( first, last) {
[Link] = first;
[Link] = last;
}
toString() {
return [Link] + " " +
[Link];
}
static checkLastName( ln) {
if (typeof ln !== "string" ||
[Link]()==="") {
[Link]("Error: invalid last name!");
}
}
}
Finally, in Step 2, a subclass is defined with additional properties and methods that possibly
override the corresponding superclass methods:
class Student extends Person {
constructor( first, last, studNo) {
[Link]( first, last);
[Link] = studNo;
}
// method overrides superclass method
toString() {
return [Link]() + "(" +
[Link] +")";
}
}
20
More on JavaScript
In ES5, we can define a base class with a subclass in the form of constructor functions, following a code
pattern recommended by Mozilla in their JavaScript Guide [[Link]
Web/JavaScript/Guide/Details_of_the_Object_Model], as shown in the following steps.
Step 1.a) First define the constructor function that implicitly defines the properties of the class by
assigning them the values of the constructor parameters when a new object is created:
function Person( first, last) {
[Link] = first;
[Link] = last;
}
Notice that within a constructor, the special variable this refers to the new object that is created when
the constructor is invoked.
Step 1.b) Next, define the instance-level methods of the class as method slots of the object referenced
by the constructor's prototype property:
[Link] = function () {
return [Link] + " " + [Link];
}
Step 1.c) Class-level ("static") methods can be defined as method slots of the constructor function itself
(recall that, since JS functions are objects, they can have slots), as in
[Link] = function (ln) {
if (typeof ln !== "string" || [Link]()==="") {
[Link]("Error: invalid last name!");
}
}
Step 1.d) Finally, define class-level ("static") properties as property slots of the constructor function:
[Link] = {};
By invoking the supertype constructor with [Link]( this, ...) for any new object created
as an instance of the subtype Student, and referenced by this, we achieve that the property slots
created in the supertype constructor (firstName and lastName) are also created for the subtype
instance, along the entire chain of supertypes within a given class hierarchy. In this way we set up
a property inheritance mechanism that makes sure that the own properties defined for an object on
creation include the own properties defined by the supertype constructors.
In Step 2b), we set up a mechanism for method inheritance via the constructor's prototype property.
We assign a new object created from the supertype's prototype object to the prototype property
of the subtype constructor and adjust the prototype's constructor property:
// Student inherits from Person
[Link] = [Link](
[Link]);
// adjust the subtype's constructor property
[Link] = Student;
21
More on JavaScript
inherited from, the superclass are also available for objects instantiating the subclass. This mechanism of
chaining the prototypes takes care of method inheritance. Notice that setting [Link]
to [Link]( [Link]) is preferable over setting it to new Person(),
which was the way to achieve the same in the time before ES5.
An instance of a constructor-based class is created by applying the new operator to the constructor and
providing suitable arguments for the constructor parameters:
var pers1 = new Person("Tom","Smith");
The method toString is invoked on the object pers1 by using the 'dot notation':
alert("The full name of the person is: " + [Link]());
When an object o is created with o = new C(...), where C references a named function
with name "C", the type (or class) name of o can be retrieved with the introspective expression
[Link], which returns "C". The Function::name property used in this
expression is supported by all browsers, except Internet Explorer versions before version 11.
In JavaScript, a prototype object is an object with method slots (and sometimes also property slots)
that can be inherited by other objects via JavaScript's method/property slot look-up mechanism. This
mechanism follows the prototype chain defined by the (in ES5 still unofficial) built-in reference
property __proto__ (with a double underscore prefix and suffix) for finding methods or properties.
As shown below in Figure 2.1, every constructor function has a reference to a prototype object as the
value of its reference property prototype. When a new object is created with the help of new, its
__proto__ property is set to the constructor's prototype property.
For instance, after creating a new object with f = new Foo(), it holds
that [Link](f), which is the same as f.__proto__, is equal to
[Link]. Consequently, changes to the slots of [Link] affect all objects that
were created with new Foo(). While every object has a __proto__ property slot (except Object),
only objects constructed with new have a constructor property slot.
Object
Function *
name[0..1] : String
length[1] : Integer
apply(in thisObj : Object, in arguments : Array) 0..1
call(in thisObj : Object, in arg1, in arg2, in ...)
bind(in thisObj : Object, in arg1, in arg2, in ...)
...() constructor
22
More on JavaScript
Notice that we can retrieve the prototype of an object with [Link](o), which
is an official ES5 alternative to o.__proto__.
Notice that the JS object Person actually represents a factory-based class. An instance of such a
factory-based class is created by invoking its create method:
var pers1 = [Link]( {firstName:"Tom", lastName:"Smith"});
The method getFullName is invoked on the object pers1 of type Person by using the 'dot
notation', like in the constructor-based approach:
alert("The full name of the person are: " + [Link]());
Notice that each property declaration for an object created with [Link] has to include the
'descriptors' writable: true and enumerable: true, as in lines 5 and 7 of the Person object
definition above.
23
More on JavaScript
front-end web app with JavaScript, the simplest approach for persistent data storage is using JavaScript's
localStorage API, which provides a simple key-value database, but does not support database
tables. So, the question is: how can we store and retrieve tables with Local Storage?
We show how to represent database tables in JavaScript in the form of (what we call) entity tables, and
how to store these tables in Local Storage.
• Maps are expressed as comma-separated lists of key-value slots enclosed in curly braces:
{"id": 2901465, "my phone number":"0049.30.227109"}
A record is a special type of map where the keys are admissible JavaScript identifiers [http://
[Link]/js-variables] denoting properties, so they need not be enclosed in quotation marks in
JavaScript code. For example, {id: 2901465, phone:"0049.30.227109"} is a record. The value of a
property in a record, or the value associated with a key in a map, may be a simple data literal, or an
array literal, or another object literal as in:
{tags:["penguin","arctis"], photographer:{"last":"Wagner","first":"Gerd"}}
An entity table contains a set of records (or table rows) such that each record represents an object with
a standard identifier property slot. Consequently, an entity table can be represented as a map of records
such that the keys of the map are the values of the standard identifier property, and their associated
values are the corresponding records, as illustrated by the following example:
A Local Storage database is created per browser and per origin, which is defined by the
combination of protocol and domain name. For instance, [Link] and http://
[Link] are different origins because they have different domain names, while http://
24
More on JavaScript
The Local Storage database managed by the browser and associated with an app (via its origin) is
exposed as the built-in JavaScript object localStorage with the methods getItem, setItem,
removeItem and clear. However, instead of invoking getItem and setItem, it is more
convenient to handle localStorage as a map, writing to it by assigning a value to a key as in
localStorage["id"] = 2901465, and retrieving data by reading the map as in var id =
localStorage["id"]. The following example shows how to create an entity table and save its
serialization to Local Storage:
var persons = {};
persons["2901465"] = {id: 2901465, name:"Tom"};
persons["3305579"] = {id: 3305579, name:"Su"};
persons["6492003"] = {id: 6492003, name:"Pete"};
try {
localStorage["personTable"] = [Link]( persons);
} catch (e) {
alert("Error when writing to Local Storage\n" + e);
}
Notice that we have used the predefined method [Link] for serializing the entity table
persons into a string that is assigned as the value of the localStorage key "personTable". We can
retrieve the table with the help of the predefined de-serialization method [Link] in the following
way:
var persons = {};
try {
persons = [Link]( localStorage["personTable"]);
} catch (e) {
alert("Error when reading from Local Storage\n" + e);
}
25
Chapter 3. Building a Minimal Web
App with Plain JS in Seven Steps
In this chapter, we show how to build a minimal front-end web application with plain JavaScript and
Local Storage. The purpose of our example app is to manage information about books. That is, we deal
with a single object type: Book, as depicted in the class diagram of Figure 3.1.
Book
isbn : String
title : String
year : Integer
The following is a sample data population for the model class Book:
What do we need for a data management app? There are four standard use cases, which have to be
supported by the app:
1. Create a new book record by allowing the user to enter the data of a book that is to be added to the
collection of stored book records.
2. Retrieve (or read) all books from the data store and show them in the form of a list.
These four standard use cases, and the corresponding data management operations, are often summarized
with the acronym CRUD.
For entering data with the help of the keyboard and the screen of our computer, we use HTML forms,
which provide the user interface technology for web applications.
For maintaining a collection of persistent data objects, we need a storage technology that allows to keep
data objects in persistent records on a secondary storage device, such as a hard-disk or a solid state disk.
Modern web browsers provide two such technologies: the simpler one is called Local Storage, and the
more powerful one is called IndexedDB. For our minimal example app, we use Local Storage.
26
Building a Minimal Web App
with Plain JS in Seven Steps
following the Model-View-Controller paradigm for software application architectures. And finally we
create an [Link] file for the app's start page, as discussed below. Thus, we end up with the
following folder structure:
MinimalApp
src
c
m
v
[Link]
In the start page HTML file of the app, we load the file [Link] and the [Link] model
class file:
The start page provides a menu for choosing one of the CRUD data management use cases. Each use
case is performed by a corresponding page such as, for instance, [Link]. The menu also
contains options for creating test data with the help of the procedure [Link]()
and for clearing all data with [Link]():
<body>
<h1>Public Library</h1>
<h2>An Example of a Minimal JavaScript Front-End App</h2>
<p>This app supports the following operations:</p>
<menu>
<li><a href="[Link]"><button type="button">
List all books
</button></a></li>
<li><a href="[Link]"><button type="button">
Add a new book
</button></a></li>
<li><a href="[Link]"><button type="button">
Update a book
</button></a></li>
<li><a href="[Link]"><button type="button">
Delete a book
</button></a></li>
<li><button type="button" onclick="[Link]()">
Clear database
</button></li>
<li><button type="button" onclick="[Link]()">
Create test data
</button></li>
</menu>
</body>
27
Building a Minimal Web App
with Plain JS in Seven Steps
In the information design model shown in Figure 3.1 above, there is only one class, representing the
object type Book. So, in the folder src/m, we create a file [Link] that initially contains the
following code:
function Book( slots) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
};
The model class Book is coded as a JavaScript constructor function with a single slots parameter,
which is a record object with fields isbn, title and year, representing the constructor parameters
to be assigned to the ISBN, the title and the year attributes of the class Book. Notice that, for getting
a simple name, we have put the class name Book in the global scope, which is okay for a small app
with only a few classes. In general, however, we should use the model namespace for model classes,
which requires class/constructor definitions like
[Link] = function (slots) {...}
In addition to defining the model class in the form of a constructor function, we also define the following
items in the [Link] file:
2. A class-level method [Link] for loading all managed Book instances from the
persistent data store.
3. A class-level method [Link] for saving all managed Book instances to the persistent data
store.
So, initially our collection of books is empty. In fact, it's defined as an empty object literal, since we
want to represent it in the form of an entity table (a map of entity records) where an ISBN is a key for
accessing the corresponding book record (as the value associated with the key). We can visualize the
structure of an entity table in the form of a lookup table, as shown in Table 3.2.
28
Building a Minimal Web App
with Plain JS in Seven Steps
Key Value
0465026567 { isbn:"0465026567," title:"Gödel, Escher, Bach",
year:1999 }
0465030793 { isbn:"0465030793," title:"I Am A Strange Loop",
year:2008 }
Notice that the values of such a map are records corresponding to table rows. Consequently, we could
also represent them in a simple table, as shown in Table 3.3.
1. Retrieving the book table that has been stored as a large string with the key "books" from Local
Storage with the help of the assignment
booksString = localStorage["books"];
2. Converting the book table string into a corresponding entity table books with book rows as elements,
with the help of the built-in procedure [Link]:
books = [Link]( booksString);
3. Converting each row of books, representing a record (an untyped object), into a corresponding
object of type Book stored as an element of the entity table [Link], with the help of
the procedure convertRec2Obj defined as a "static" (class-level) method in the Book class:
Book.convertRec2Obj = function (bookRow) {
var book = new Book( bookRow);
return book;
};
29
Building a Minimal Web App
with Plain JS in Seven Steps
booksString="", books={};
try {
if (localStorage["books"]) {
booksString = localStorage["books"];
}
} catch (e) {
alert("Error when reading from Local Storage\n" + e);
}
if (booksString) {
books = [Link]( booksString);
keys = [Link]( books);
[Link]( [Link] +" books loaded.");
for (i=0; i < [Link]; i++) {
key = keys[i];
[Link][key] = Book.convertRec2Obj( books[key]);
}
}
};
Notice that since an input operation like localStorage["books"] may fail, we perform it in a
try-catch block, where we can follow up with an error message whenever the input operation fails.
Notice that in the case of a numeric attribute (such as year), we have to make sure that the value
of the corresponding input parameter (y), which is typically obtained from user input via an HTML
form, is converted from string to number with one of the two type conversion functions parseInt
or parseFloat.
1. Converting the entity table [Link] into a string with the help of the predefined
JavaScript procedure [Link]:
30
Building a Minimal Web App
with Plain JS in Seven Steps
booksString = [Link]( [Link]);
2. Writing the resulting string as the value of the key "books" to Local Storage:
localStorage["books"] = booksString;
These two steps are performed in line 5 and in line 6 of the following program listing:
[Link] = function () {
var booksString="", error=false,
nmrOfBooks = [Link]( [Link]).length;
try {
booksString = [Link]( [Link]);
localStorage["books"] = booksString;
} catch (e) {
alert("Error when writing to Local Storage\n" + e);
error = true;
}
if (!error) [Link]( nmrOfBooks + " books saved.");
};
Here, the main namespace is defined to be pl, standing for "Public Library", with the three
subnamespaces m, v and c being initially empty objects. We put this code in a separate file
31
Building a Minimal Web App
with Plain JS in Seven Steps
[Link] in the c folder, because such a namespace definition belongs to the controller part
of the application code.
For a data management use case with user input, such as "Create", an HTML form is required as a user
interface. The form typically has a labelled input or select field for each attribute of the model class:
<body>
<header>
<h1>Create a new book record</h1>
</header>
<main>
<form id="Book">
<div><label>ISBN: <input name="isbn" /></label></div>
<div><label>Title: <input name="title" /></label></div>
<div><label>Year: <input name="year" /></label></div>
<div><button type="button" name="commit">Save</button></div>
</form>
</main>
<footer>
<a href="[Link]">Back to main menu</a>
</footer>
</body>
1. setupUserInterface takes care of retrieving the collection of all objects from the persistent
data store and setting up an event handler (handleSaveButtonClickEvent) on the save button
for handling click button events by saving the user input data;
2. handleSaveButtonClickEvent reads the user input data from the form fields and then saves
this data by calling the [Link] procedure.
[Link] = {
setupUserInterface: function () {
var saveButton = [Link]['Book'].commit;
// load all book objects
[Link]();
// set an event handler for the save/submit button
[Link]("click",
[Link]);
32
Building a Minimal Web App
with Plain JS in Seven Steps
// handle the event when the browser window/tab is closed
[Link]("beforeunload", function () {
[Link]();
});
},
handleSaveButtonClickEvent: function () {
var formEl = [Link]['Book'];
var slots = { isbn: [Link],
title: [Link],
year: [Link]};
[Link]( slots);
[Link]();
}
};
For our example app, this page is called [Link], located in the main
folder MinimalApp, and it contains the following code in its head element:
<head>
<meta charset="UTF-8" />
<title>Simple JS Front-End App Example</title>
<script src="src/c/[Link]"></script>
<script src="src/m/[Link]"></script>
<script src="src/v/[Link]"></script>
<script>
[Link]( "load",
[Link]);
</script>
</head>
Notice that, in addition to loading the app initialization JS file and the model class JS file, we load the
view code file (here: [Link]) and invoke its setupUserInterface
procedure via a load event listener. This is the pattern we use for all four CRUD use cases.
<body>
<header>
<h1>Retrieve and list all book records</h1>
</header>
<main>
<table id="books">
<thead><tr><th>ISBN</th><th>Title</th><th>Year</th></tr></thead>
<tbody></tbody>
</table>
</main>
<footer>
<a href="[Link]">Back to main menu</a>
</footer>
</body>
In the setupUserInterface procedure, we first set up the data management context by retrieving
all book data from the database and then fill the table by creating a table row for each book object from
[Link]:
[Link] = {
setupUserInterface: function () {
var tableBodyEl = [Link]("table#books>tbody");
var keys=[], key="", row={}, i=0;
// load all book objects
[Link]();
keys = [Link]( [Link]);
33
Building a Minimal Web App
with Plain JS in Seven Steps
// for each book, create a table row with cells for the 3 attributes
for (i=0; i < [Link]; i++) {
key = keys[i];
row = [Link]();
[Link](-1).textContent = [Link][key].isbn;
[Link](-1).textContent = [Link][key].title;
[Link](-1).textContent = [Link][key].year;
}
}
};
More specifically, the procedure setupUserInterface creates the view table in a loop over all
objects of [Link]. In each step of this loop, a new row is created in the table body element
with the help of the JavaScript DOM operation insertRow(), and then three cells are created in
this row with the help of the DOM operation insertCell(): the first one for the isbn property
value of the book object, and the second and third ones for its title and year property values. Both
insertRow and insertCell have to be invoked with the argument -1 for making sure that new
elements are appended to the list of rows and cells.
Notice that we include a kind of empty option element, with a value of "" and a display text of ---
, as a default choice in the selectBook selection list element. So, by default, the value of the
selectBook form control is empty, requiring the user to choose one of the available options for filling
the form.
The setupUserInterface procedure now has to populate the select element's option list by
loading the collection of all book objects from the data store and creating an option element for each
book object:
[Link] = {
setupUserInterface: function () {
var formEl = [Link]['Book'],
saveButton = [Link],
selectBookEl = [Link];
var key="", keys=[], book=null, optionEl=null, i=0;
[Link]();
// populate the selection list with books
keys = [Link]( [Link]);
for (i=0; i < [Link]; i++) {
key = keys[i];
book = [Link][key];
34
Building a Minimal Web App
with Plain JS in Seven Steps
optionEl = [Link]("option");
[Link] = [Link];
[Link] = [Link];
[Link]( optionEl, null);
}
// when a book is selected, populate the form
[Link]("change",
[Link]);
// set an event handler for the submit/save button
[Link]("click",
[Link]);
// handle the event when the browser window/tab is closed
[Link]("beforeunload", [Link]);
},
...
}
A book selection event is caught via a listener for change events on the select element. When a
book is selected, the form is filled with its data:
handleBookSelectionEvent: function () {
var formEl = [Link]['Book'];
var selectBookEl = [Link],
book=null, key = [Link];
if (key) {
book = [Link][key];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
} else {
[Link]();
}
},
When the save button is activated, a slots record is created from the form field values and used as
the argument for calling [Link]:
handleSaveButtonClickEvent: function () {
var formEl = [Link]['Book'];
var slots = { isbn: [Link],
title: [Link],
year: [Link]
};
[Link]( slots);
[Link]();
}
Like in the Update case, the setupUserInterface procedure in the view code in src/v/
[Link] loads the book data into main memory, populates the book selection list and adds
some event listeners. The event handler for Delete button click events.
handleDeleteButtonClickEvent: function () {
35
Building a Minimal Web App
with Plain JS in Seven Steps
var selectEl = [Link]['Book'].selectBook;
var isbn = [Link];
if (isbn) {
[Link]( isbn);
// remove deleted book from select options
[Link]( [Link]);
}
}
Alternatively, for remotely storing the application data with the help of a web API one can either use a
back-end solution component or a cloud storage service. The remote storage approach allows managing
larger databases and supports multi-user apps.
Today, the UI pages of a web app have to be adaptive (frequently called "responsive") for being rendered
on different devices with different screen sizes and resolutions, which can be detected with CSS media
queries. The main issue of an adaptive UI is to have a fluid layout, in addition to proper viewport settings.
Whenever images are used in a UI, we also need an approach for adaptive bitmap images: serving images
in smaller sizes for smaller screens and in higher resolutions for high resolution screens, while preferring
scalable SVG images for diagrams and artwork. In addition, we may decrease the font-size of headings
and suppress unimportant content items on smaller screens.
For our purposes, and for keeping things simple, we customize the adaptive web page design
defined by the HTML5 Boilerplate [[Link] project (more precisely, the minimal
"responsive" configuration available on [Link]). It just consists of an HTML template file
and two CSS files: the browser style normalization file [Link] (in its minified form) and
a [Link], which contains the HTML5 Boilerplate style and our customizations. Consequently, we
use a new css subfolder containing these two CSS files:
MinimalApp-with-CSS
css
[Link]
36
Building a Minimal Web App
with Plain JS in Seven Steps
[Link]
src
c
m
v
[Link]
One customization change we have made in [Link] is to replace the <div class="main">
container element with the new HTML 5.1 element <main> such that we obtain a simple and clear
UI page structure provided by the sequence of the three container elements <header>, <main> and
<footer>. This change in the HTML file requires corresponding changes in [Link]. In addition,
we define our own styles for <table>, <menu> and <form> elements. Concerning the styling of
HTML forms, we define a simple style for implicitly labeled form control elements.
The start page [Link] now must take care of loading the CSS page styling files with the help
of the following two link elements:
<link rel="stylesheet" href="css/[Link]">
<link rel="stylesheet" href="css/[Link]">
Since the styling of user interfaces is not our primary concern, we do not discuss the details of it and
leave it to our readers to take a closer look. You can run the CSS-styled minimal app [[Link]
[Link]/tech/JsFrontendApp/MinimalApp-with-CSS/[Link]] from our server or download
its code [[Link] as a ZIP archive
file.
37
Building a Minimal Web App
with Plain JS in Seven Steps
For instance, in our example app, we have the integer-valued attribute year. When the user has entered
a value for this attribute in a corresponding form field, in the Create or Update user interface, the form
field holds a string value, which has to be converted to an integer in an assignment like the following:
[Link] = parseInt( [Link]);
One important question is: where should we take care of de-serialization: in the "view" (before the value
is passed to the "model" layer), or in the "model"? Since attribute range types are a business concern,
and the business logic of an app is supposed to be encapsulated in the "model", de-serialization should
be performed in the "model" layer, and not in the "view".
The original MVC proposal included a data binding mechanism for automated one-way model-to-view
synchronization (updating the model's views whenever a change in the model data occurs). We didn't
take care of this in our minimal app because a front-end app with local storage doesn't really have
multiple concurrent users. However, we can create a (rather artificial) situation that illustrates the issue:
1. Open the Update UI page of the minimal app twice (for instance, by opening
[Link] twice), such that you get two browser tabs rendering the same
page.
2. Select the same learning unit on both tabs, such that you see its data in the Update view.
3. Change one data item of this learning unit on one of the tabs and save your change.
4. When you now go to the other tab, you still see the old data value, while you may have expected that
it would have been automatically updated.
A mechanism for automatically updating all views of a model object whenever a change in its property
values occurs is provided by the observer pattern that treats any view as an observer of its model object.
Applying the observer pattern requires that (1) model objects can have a multi-valued reference property
like observers, which holds a set of references to view objects; (2) a notify method can be invoked on
view objects by the model object whenever one of its property values is changed; and (3) the notify
method defined for view objects takes care of refreshing the user interface.
Notice, however, that the general model-view synchronization problem is not really solved by
automatically updating all (other users') views of a model object whenever a change in its data occurs.
38
Building a Minimal Web App
with Plain JS in Seven Steps
Because this would only help, if the users of these views didn't make themselves any change of the data
item concerned, meanwhile. Otherwise, their changed data value would be overwritten by the automated
refresh, and they may not even notice this, which is not acceptable in terms of usability.
1. the user interface (UI) code because it should be possible to re-use the same model classes with
different UI technologies;
2. the storage management code because it should be possible to re-use the same model classes with
different storage technologies.
In this tutorial, we have kept the model class Book independent of the UI code, since it does not contain
any references to UI elements, nor does it invoke any view method. However, for simplicity, we didn't
keep it independent of storage management code, since we have included the method definitions for add,
update, destroy, etc., which invoke the storage management methods of JavaScrpt's localStorage
API. Therefore, the separation of concerns is incomplete in our minimal example app.
The app deals with just one object type: Movie, as depicted in Figure 3.3 below. In the subsequent parts
of the tutorial, you will extend this simple app by adding integrity constraints, enumeration attributes,
further model classes for actors and directors, and the associations between them.
Notice that releaseDate is an attribute with range Date, so you need to find out how to display,
and support user input of, calendar dates.
Movie
movieId : Integer
title : String
releaseDate : Date
For developing the app, simply follow the sequence of seven steps described in the tutorial:
39
Building a Minimal Web App
with Plain JS in Seven Steps
2. international characters are supported by using UTF-8 encoding for all HTML files,
40
Glossary
C
CRUD CRUD is an acronym for Create, Read/Retrieve, Update, Delete,
which denote the four basic data management operations to be
performed by any software application.
D
Document Object Model An abstract API for retrieving and modifying nodes and elements of
HTML or XML documents. All web programming languages have
DOM bindings that realize the DOM.
Domain Name System The DNS translates user-friendly domain names to IP addresses that
allow to locate a host computer on the Internet.
E
ECMAScript A standard for JavaScript defined by the industry organization "Ecma
International".
Extensible Markup XML allows to mark up the structure of all kinds of documents, data
Language files and messages in a machine-readable way. XML may also be
human-readable, if the tag names used are self-explaining. XML is
based on Unicode. SVG and MathML are based on XML, and there is
an XML-based version of HTML.
H
Hypertext Markup Language HTML allows marking up (or describing) the structure of a human-
readable web document or web user interface. The XML-based version
of HTML, which is called "XHTML5", provides a simpler and cleaner
syntax compared to traditional HTML.
Hypertext Transfer Protocol HTTP is a stateless request/response protocol based on the Internet
technologies TCP/IP and DNS, using human-readable text messages
for the communication between web clients and web servers. The main
purpose of HTTP has been to allow fetching web documents identified
by URLs from a web browser, and invoking the operations of a back-
end web application program from a HTML form executed by a web
browser. More recently, HTTP is increasingly used for providing web
APIs and web services.
41
Glossary
I
IANA IANA stands for Internet Assigned Numbers Authority, which is a
subsidiary of ICANN responsible for names and numbers used by
Internet protocols.
I18N A set of best practices that help to adapt products to any target language
and culture. It deals with multiple character sets, units of measure,
keyboard layouts, time and date formats, and text directions.
J
JSON JSON stands for JavaScript Object Notation, which is a data-
interchange format following the JavaScript syntax for object literals.
Many programming languages support JSON as a light-weight
alternative to XML.
M
MathML An open standard for representing mathematical expressions, either in
data interchange or for rendering them within webpages.
MIME A MIME type (also called "media type" or "content type") is a keyword
string sent along with a file for indicating its content type. For example,
a sound file might be labeled audio/ogg, or an image file image/
png.
P
PNG PNG stands for Portable Network Graphics, which is a open
(non-proprietary) graphics file format that supports lossless data
compression.
R
RDF RDF stands for Resource Description Framework, which is a W3C
language for representing machine-readable propositional information
on the web.
42
Glossary
S
SGML SGML stands for Standard Generalized Markup Language, which is
an ISO specification for defining markup languages. HTML4 has been
defined with SGML. XML is a simplified successor of SGML. HTML5
is no longer SGML-based and has its own parsing rules.
U
Unicode A platform-independent character set that includes almost all
characters from most of the world's script languages including Hindi,
Burmese and Gaelic. Each character is assigned a unique integer code
in the range between 0 and 1,114,111. For example, the Greek letter
π has the code 960. Unicode includes legacy character sets like ASCII
and ISO-8859-1 (Latin-1) as subsets.
URI URI stands for Uniform Resource Identifier, which is either a URL or
a URN.
URL URL stands for Uniform Resource Locator, which is a resource name
that contains a web address for locating the resource on the web.
URN URN stands for Uniform Resource Name, which refers to a resource
without specifying its location.
User Agent A user agent is a front-end web client program such as a web browser.
W
WebM WebM is an open (royatly-free) web video format supported by Google
Chrome and Mozila Firefox, but not by Microsoft Internet Explorer
and Apple Safari.
43
Glossary
World Wide Web The WWW (or, simply, "the web") is a huge client-server network
based on HTTP, HTML and XML, where web browsers (and other
'user agents'), acting as HTTP clients, access web server programs,
acting as HTTP servers.
W3C W3C stands for World Wide Web Consortium, which is an international
organization in charge of developing and maintaining web standards.
44