History for Ajax pages

If you write dynamic JavaScript web pages you know about the nuisance of not having the browser managing back and forward buttons for your code. There is a number of solutions to overcome this issue, in my team we tested a few of them, than we shortlisted the candidates to history.js and backbone.js, and I think we are about to use the latter.

If you need some background on the matter, you could have a look at these pages:
Mark Pilgrim put on the web some material from his book on HTML5, here is a chapter on the history API
On Google Developers, a getting started document on Ajax crawling
On the Mozilla Developer Network, an article on Manipulating the browser history
A description of the solution provided by history.js is available on github.
Also on github you can get information on backbone.js.

The point is that we can't just rely on the HTML5 solution, the so called History API (or pushState), because we should support also clients that are using older browser. Before pushState, a few indipendent solutions were designed to tweak the fragment identifier support offered by HTML4, see this page on w3.org for details, to achieve the same result. What history.js, backbone.js, and others do is providing a way to keep the code specific to each platform localized in a place.

I am going to create a simple tiny web page with history support provided by backbone.js, and to do that I need to have at hand a couple of libraries, actually, three of them: jQuery, underscore.js, and backbone itself.

The changes to my pages are driven by three links, each of them generating an event, which should result on setting some text in a div. Admittedly, nothing fancy. But bear with me.

The HTML would be something like this:
<div id="msg">Hello backbone</div>
<hr />
<p><a href="#event/id/3">Event id 3</a></p>
<p><a href="#event/id/5">Event id 5</a></p>
<p><a href="#event/id/7">Event id 7</a></p>
The interesting part is the JavaScript code, just a couple of (dense) lines:
new (Backbone.Router.extend({ // 1
  routes: { "event/id/:id": "processEvent" }, // 2
  processEvent: function(id) { $('#msg').text('Event id ' + id); } // 3
}));

Backbone.history.start(); // 4
1. An object is created here. It is an Backbone.Router extended by the object passed, that contains two properties.
2. This routes property is used to route the event generated by the user JavaScript to what it should do. Going to the backbone router we could delegate to it the job of taking care of the history. What we say to backbone here is to get each link in the format "event/id/" plus a parameter and call a function with the name specified as value (here I've chosen the name "processEvent").
3. The name of the second property should match with the value in the object defined above (I mean, "processEvent"), and its value is the function that I want to be executed by the backbone router on my request. Here I get the div with id msg, and I set its text to a different string accordingly to the passed parameter.
4. I'm ready, so I ask backbone to start the history.

Now what happens is that clicking on the link the user changes the page content and its URL in the address bar. The browser history will work fine, and we can copy the page URL, and open it in a different browser to get the expected behavior.

Go to the full post

Module pattern template

My current project makes use of different technologies, for presentation we rely on a mix of Java EE and JavaScript. We try not to mess around too much with the latter, and we strive to keep that code as readable as possible. For this reason we break the JavaScript code in modules that, ideally, are all written following the same template, so that it is easy for anyone in the team to put his hands on any piece of code available.

Here is an example of how we typically write a module.

As you will see, we use the well known module pattern, with a few specific variations:
var APP = APP || {}; // 1

APP.Module = (function(app, global, $) { // 2
  "use strict"; // 3

  var FIRM_NAME = 'XYZ'; // 4

  function Factory(options) { // 5
    var that = this; // 6

    if(!(this instanceof Factory)) { // 7
      return new Factory();
    }

    this.options = $.extend({ name: null }, options); // 8

    function _checkName() { // 9
      if(that.options.name) {
        console.log('In a private function, use that instead of this');
        return true;
      }
      else {
        return false;
      }
    }

    this.getName = function getName() { // 10
      return FIRM_NAME + (_checkName() ? ': ' + this.options.name : '');
    }

    return this; // 11
  }

  Factory.aFunction = function() { // 12
    if(this == Factory) {
      console.log('A static function has no access to instance variables');
    }
    else { // called by sayHello, see below
      console.log('Instance', this.options.name);
    }
  }

  Factory.prototype.sayHello = Factory.aFunction; // 13

  return Factory; // 14
}(APP, this, jQuery)); // 15
1. First thing, I define a namespace for all the modules. Or better, if APP is already defined, I use it as it is in the following code. Only if no APP is already available a create it from scratch.
2. In APP, I create a module named Module (usually it is a good idea choosing a better name). As you see, it is nothing more that an immediate function that receives in input three parameters, see the module last line (point 15.) to find out what they are.
3. The JavaScript code used is "strict".
4. This is a private variable (ideally, a constant) available to all the Module instances.
5. The Module's constructor. It accepts in input a variable used to set the internal object properties. In this case "options" contains just a single value, so it is an overkill not to use it. But usually options contains a large number of properties.
6. The infamous "this is that" pattern. Follow the link for more details.
7. Another well known JavaScript pattern. The constructor could be called improperly, with this check we avoid any unpleasant surprise.
8. We use jQuery, so to extends the "options" object passed to the constructor we use the jQuery .extend() function. Same functionality is provided by other frameworks, and it could also implemented with no special trouble by hands. The idea is that we want to ensure that our local "options" contains at least a property named "name". If the passed "options" has it, we will keep it, otherwise a new, empty one (or better, null), is created.
9. A private function. No one could access it outside its scope. Notice that inside it we have to use "that" to access the constructor "this".
10. A public function. It could be called from outside, and it has full access to the constructor and module properties.
11. As almost any constructor, at the end of its job it returns "this".
12. Sometimes it is useful to have a "static" (in the C++/Java sense) method in a module. Here is how we can emulate it. We can even use a trick (see 13.) to adapt this method so that it could also be called as a non-static function.
13. Here is the trick. We create a property in the Factory prototype, and we assign to it the static function. Neat.
14. Finally, the immediate function calls the constructor, so that the object is created.
15. We call the immediate function passing to it APP (the module's namespace), the current "this" (at this point it should be the global one), and jQuery (since we use it - you could pass your preferred framework instead, obviously. Or you could even pass many ones).

Here is a test usage for the above defined module:
var m1 = new APP.Module({name: 'John Smith'}); // 1
console.log(m1.getName());

var m2 = new APP.Module(); // 2
console.log(m2.getName());

APP.Module.aFunction(); // 3
console.log("Can't call a private function from outside:", m1._checkName === undefined);
console.log("Can't call an instance function from static context:", APP.Module.sayHello === undefined);
console.log("Can't call a static function from an object:", m1.aFunction === undefined);
m1.sayHello(); // 4
1. An object m1 is created, passing a name to the module.
2. Here we create an "anonymous" module, no name it is passed.
3. The static function is called on the module itself, it doesn't requires an actual instance.
4. But through that clever trick showed above on (13.) we can call the static function through an alias.

Go to the full post

Reading a JSON and looping on it

I have a JSON array of strings stored in a file, I want to read it from a JavaScript and use in someway its values. To simplify the file access, I am about to use the jQuery getJSON() function.

The JSON file, named numbers.json, contains something like this:
["Zero", "One", "Two", "Three"]

This JavaScript fragment gets asynchronously the file, and then dumps to the console any elements in the fetched JSON:
$.getJSON('numbers.json').done(function(numbers) {
  for(var i=0; i < numbers.length; ++i) {
    console.log(numbers[i]);
  }
});
Calling getJSON() we ask jQuery to fetch the content of the passed filename and, when done, calling the anonymous function passed as parameter to done(), putting in its input parameter, that I named numbers, the contained JSON. In the body of that anonymous function we have to deal with the fetched data. What I do there is simply looping on the array, and logging to the console each component.

Go to the full post

From Java objects to Json

I am pretty busy in these days. Just a few lines to remember to myself that I have a couple of blogs to think about, and it would be good write something on them once in a while.

Currently I am working on a servlet that also generates a few Json responses on request. It happens. Json is much popular in JavaScript environment (and not only there), and one should be prepared to convert data to and from that format.

That servlet I am working on, currently does this job "by hand" (yuck!) polluting the code with obscure short strings that makes a nightmare maintaining it.

A few better solutions exist. I had a fast look around and I picked up the google-gson library, that looks to me simple and powerful enough for my current requirements.

As you could guess from its name, google-gson is a project hosted by Google Code. You would find there its home page. There you could also get the latest version (currently 2.2.2) and enough documentation to start working with it.

I have written a few test cases, just to check it before start using it in the real code, but nothing worth to be written here. Have a look instead to their user guide, that includes a few examples that should be enough to let you see how it works.

Go to the full post

From XML to object

We have seen how easy is to marshal a Java object to XML when using JAXB, now I am showing you how to unmarshal an XML in a (compatible) Java object using the same library.

We have this XML fragment:
<user id="42" rating="4.2">Bill</user>
And we want to get from it an instance of the class User, as defined in the previous post. The (minor) nuisance is that I have to annotate User so that JAXB knows how it should map its data member to the XML elements, values, and attributes. Once this is done, we get the job done in a matter of few lines:
public User xml2Obj(String xml) { // 1
    try {
        JAXBContext ctx = JAXBContext.newInstance(User.class); // 2
        Unmarshaller um = ctx.createUnmarshaller(); // 3

        StringReader sr = new StringReader(xml);
        User user = (User) um.unmarshal(sr); // 4
        return user;
    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    }
}
1. This function gets in input the XML to be unmarshalled, and gives back the resulting User object (or null, in case of error).
2. A JAXB context is needed to do the magic, and it should know on which class it operates.
3. A JAXB marshaller is the guy that is going to do the dirty job.
4. To keep the unmarshaller code simple, it has been designed to operate on readers. So, the XML String is passed to a StringReader to adapt it to the JAXB expectations.

The full Java source code for the User class and a Main class using it are on github. The example includes both marshalling (as seen in the previous post) and unmarshalling.

Go to the full post

From object to XML

JAXB (Java Architecture for XML Binding) provides an easy way of converting Java objects to XML. In the JAXB jargon, this is know as marshalling, where unmarshalling means the opposite action of extracting a Java object from an XML.

As a first example, let's see how to create an XML fragment like this:
<user id="42" rating="4.2">Bill</user>
from a Java class named User that has the user name, id, and rating as data member.

Even if this looks like a pretty simple job, still there are a couple of points that it could be interesting to pay attention to. Large part of the JAXB job is done by annotations, with the result that the code looks quite simple to understand at first sight, once you know what it is going on.

In this case, I want my class User to have a couple of annotations, one to state that it represents a root XML element, and the second one to let JAXB know that I want to put an annotation to the data fields, and not to their getters, to specify their XML role.

The result is something like this:
@XmlRootElement // 1
@XmlAccessorType(XmlAccessType.FIELD) // 2
public class User {
    @XmlValue
    private String name;
    @XmlAttribute
    private int id;
    @XmlAttribute
    private float rating;

    // getters and setters follow ...
}
1. This class is the root element for my XML
2. If you don't explicitly say that the accessor type should be found in the field definition, JAXB gets confused. If you comment this line out, you get an IllegalAnnotationsException, and a message saying that "Class has two properties of the same name".

Once you have defined your JAXB annotated class, it is just a matter of creating an object, and marshalling:
public String obj2xml(User user) {  
    try {
        JAXBContext ctx = JAXBContext.newInstance(User.class); // 1
        Marshaller marshaller = ctx.createMarshaller(); // 2
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // 3

        StringWriter sw = new StringWriter();
        marshaller.marshal(user, sw); // 4
        return sw.toString();
    }
    catch (JAXBException e) { // 5
        e.printStackTrace();
        return "<bad />";
    }
}
1. Create a JAXB context that knows about the User class.
2. Then from the context we get a marshaller.
3. Here I want to generate just an XML fragment, if I want to generate a full XML document, I would remove this line, and the generated XML would have this header:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4. Ask the marshaller to send its output to a StringWriter, from which the resulting XML could be extracted as a String.
5. In case of anything goes wrong, give an alarming feedback to the user (not a very polite thing to do, but here it will suffices) but still return a valid XML.

The full Java source code for the User class and a Main class using it are on github.

Go to the full post

Three solutions to the loop problem

The lack of a block scope in JavaScript leads to what is often called The Infamous Loop Problem, where we try to use the (supposed) cycle variable in a for loop to set a callback function.

Conceptually, the solution is quite easy. The trouble is caused by the loop variable, that actually does not have a local scope, so we provide to it a local scope. In JavaScript we have only function scope, so a function would help us to find a way out.

The question is, which function? Whichever it is better for you in your context, I'd say. Let's see the three answers that I guess are more natural.

In the previous post I have written a buggy piece of code that was storing a few functions when looping on an array, an then, in another for loop, it called those functions. Now I modify it to let it work as I expected, following three different approaches.

Closure in loop

This is the most idiomatic solution using "pure" JavaScript. We wrap the code in the for loop around a closure, designed just to provide a local scope for the loop variable.
function doSomething(msg) {
    console.log(msg);
}

var messages = [ "hello", 42, { pi: 3.14 } ];
var buffer = [];

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = (function(j) { // 1
        return function() { // 2
            doSomething(messages[j]);
        }
    })(i); // 3
}

// ...

for(var k = 0; k < buffer.length; ++k) {
    buffer[k]();
}
1. We put in buffer the function returned by a closure, here defined, that take as input a parameter, named j, that is assigned a value defined in (3).
2. The function returned by the closure is almost the same function we defined in the original code. The difference is that I don't use anymore the loop variable, but the closure parameter.
3. This is the core of the solution. I assigned to the closure parameter the loop variable, in this way the closure captures its current value, that now has a local scope, as required.

After a while, I guess this would look as the most natural approach, but if your JavaScript mileage is low, you could be find it a bit overwhelming. In this case, maybe you could be more at ease with the following variation.

Closure in the function

The idea is to move the closure from the for loop to the recipient function. I refactor the code above, rewriting the for loop and doSomething(), renamed doSomethingElse() for the sake of clarity.
function doSomethingElse(index) {
    return function() { // 1
        console.log(messages[index]);
    }
}

// ...

for(var i = 0; i < messages.length; ++i) {
    buffer[i] = doSomethingElse(i); // 2
}

// ...
1. The closure has been moved here. Notice that this function does not run any code, but returns a function.
2. Just a simple assignment!

This code is so much readable, but I am losing the connection between the loop (2) and the reason why I need a closure in (1). Someone who reads just doSomethingElse() would probably wonder why it returns a closure instead of doing directly its job.

jQuery.each()

If we use the jQuery library, we can get the advantages of both the previous solutions using the each() method.

We use the original doSomething() function, and we don't need a closure in the for loop, jQuery.each() is a function, so it provides its own scope.
$.each(messages, function(index, value) { // 1
    buffer[index] = function() { // 2
        doSomething(value);
    }
});
1. For each element in the messages array, we call a function where the first parameter is the current index, and value the message element currently accessed.
2. There's no need of a closure, we simply assign to the buffer element a function that calls doSomething(). The capturing of local values is performed by jQuery.each().

Go to the full post