Today, I was thinking about adding undo/redo functionality in a form editor I have been working on lately. So I decided to look around to see if there are any libraries or implementations I could use. Couldn’t find anything to my liking, most of them use elaborate patterns (memento, etc….) or simply resort to saving the whole application state which is overkill, so I developed my own undo/redo thing.
In any Flex application, when you perform an action against some component, what you are actually doing is applying a forward transformation to the application state at one time to produce a different state at another time. Likewise, when an inverse transformation is applied to the current application state, we end-up with the original state.
The main idea is to simply use a closure to capture any transformation with all the necessary data which are used in the transformation logic. The result of this will be a stateless function that can be called any time. Thus for undo/redo, the forward transformation and its reverse are captured resulting in two distinct stateless functions. Both of undo and redo functions could be stored in an array and called at will without worrying about the current state of the application.
But what are the conditions that would ensure the consistency of the application state with the undo/redo logic at all times? Basically just one, it is the requirement that every action performed in the application be captured in a separate closure.
For example:
for which the code is:
<?xml version="1.0" encoding="utf-8"?> |
The array _history holds the undo/redo history, and _index points to the most recent undo or redo operation that has been executed. The function closureFactory takes a generic function along with its arguments then returns a closure. This function is used in application logic (moveLogic) to create the two undo and redo closures and to save them into _history using the function _updateHistory. In closureFactory, I have used apply to pass a variable number of arguments into transforms’ argument list.
Note that only when the label is actually entitled to move, _history is updated with a new closure. Otherwise we would end up with a lot of dummy do-nothing undo/redo actions!
Comments, questions and suggestions are welcomed,
0 comments:
Post a Comment