Something to remember -- Object state
Januari 29, 2007
So I was thinking to myself, whilst bumping the back of my head against the stairs (bump, bump, bump):
- Wouldn't it be nice if I could get a js object to
remember its last state (ie the values of all of its properties) and the state before that and so on.
- Wouldn't it be nice if I could undo the undoing as well?
- Could I manage to do this without leaving any mark on the Object.prototype or any object property at all for that matter?
So here it is, ready to be introduced to you:
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.
How to use
Now you have a new object called objState available, with two methods to use:
- ojbState.add(obj) -- returns a new state of the object.
- objState.get(obj,co) -- returns another state of the obj (an older one if co<0).
The objState.get method can be used with a third parameter as well:
- objState.get(obj,startCo,endCo) -- returns an array of objects
Confusing? Let's hope the example below will make it clearer.
Here we add and alter som properties of an object whilst using objState:
// create obj - an object with the name "Albert"
// add a new state of obj (and replace obj with it)
// alter the name of obj
// add a new state again (and replace obj with it)
// alter the name of obj again
// add an age to to the previous state of obj
Now let's have a look at the property values at different states:
// get all states of obj as an array - a
// let's have a look at the property values of the different states
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).