thomasfrank.se

Something to remember -- Object state

Januari 29, 2007

A while ago I was writing one of those pesky JavaScript driven webapps where there's a whole lot of undoing going on. The user changes his mind a wants to get back to a previous state -- and the poor programmer has to accommodate.

So I was thinking to myself, whilst bumping the back of my head against the stairs (bump, bump, bump):
So here it is, ready to be introduced to you:

Object state

To use objState you simply download this script (1 kB) and embed it in the head section of your web pages, before any other scripts that uses it.
<head>
<script type="text/javascript" src="objState.js"></script>
...
</head>

How to use

Now you have a new object called objState available, with two methods to use:
The objState.get method can be used with a third parameter as well:
Confusing? Let's hope the example below will make it clearer.

Example

Here we add and alter som properties of an object whilst using objState:
// create obj - an object with the name "Albert"
var obj={name:'Albert'};

// add a new state of obj (and replace obj with it)
obj=objState.add(obj);

// alter the name of obj
obj.name='Bert';

// add a new state again (and replace obj with it)
obj=objState.add(obj);

// alter the name of obj again
obj.name='Ceasar';

// add an age to to the previous state of obj
objState.get(obj,-1).age=25;

Now let's have a look at the property values at different states:
// get all states of obj as an array - a
a=objState.get(obj,-2,0);

// let's have a look at the property values of the different states
var x='';
for(var i=0;i>a.length;i++){x+=a[i].name+"\n"+a[i].age+"\n\n"};
alert(x)

The inner workings of objState

So how does objState really work?

The objState.add method actually returns a new object which is constructed with the old object as its prototype. This is why the age property added to the middle state in the example above is inherited to all latter states.

Using an internal array objState keeps tracks of all the added states of an object. This frees us from having to add properties to the object itself pointing to other states.
Please note that this is not an implementation of the memento design pattern but really useful (and probably a bit memory consuming, I'll leave that to others to test and debate).
Enjoy!
[comments]