HTML5 and JavaScript

If you are not a programmer, this post won’t interest you.

I’ve continued a little on my HTML5 experiment, which you can see here if you are using the latest and greatest Firefox, Safari, or Chrome. I’ve added Undo and Redo – use [Cmd] + Z for undo, and [Cmd] + [Shift] + Z for redo.

Adding Undo and Redo seems complicated unless you know one of the proven software design patterns for implementing this. For example, the Command pattern. Each action, such as moving a shape around, has a Command object, which contains two methods: one to perform the move, and one to perform the undo. These are kept in an undo stack. When the user performs an undo, you pop the stack, call the undo method on the command object you popped, then push the command object onto the redo stack.

JavaScript makes it extremely easy to implement this, because of its first-class functions, aka lambdas; and the low-hassle way to create objects. Creating an object can be done on the fly without any class definition:

         function createCommand(name, executeFunction, undoFunction) {
     return {name: name, execute: executeFunction, undo: undoFunction};

It is similar to a factory constructor in Java.

Using that function, I can create a command to, for example, handle moving and undo for moving as follows:

        var executeFunction = function() {
shape.x = newX;
shape.y = newY;
var undoFunction = function() {
shape.x = oldX;
shape.y = oldY;
var command = createCommand(

After spending recent years programming mostly in Java and a little in Objective-C, I have mixed feelings about these JavaScript constructs. It is awfully easy and concise to code features such as Undo and Redo. On the other hand, the code lacks all type-safety features that catch many simple programming mistakes at compile-time.