theme selector

light blue screenshot grey screenshot navy screenshot dark green screenshot red and black screenshot
 

by Tony Chang
tony@ponderer.org

All opinions on this site are my own and do not represent those of my employer.

Creative Commons Attribution License

edit/undo

May 26, 2005, 10:11pm EDT

 

 

Aaron asks for favorite javascript idioms. Well, this isn’t an idiom, but I do like how closures make it very easy to implement undo/redo functionality [1] in a web application.

For example, in an drawing application, I may want to enable the user to undo/redo the creation of a line. To do this, I would create an object that holds the undo and redo state:

var objId = DrawLine(startPoint, endPoint);
var state = {
  ‘undo’: function() {
    DeleteObject(objId);
  },
  ‘redo’: function() {
    DrawLineWithId(startPoint, endPoint, objId);
  }
};

Then I would have two stacks that hold state objects, one for undo and one for redo. New state objects get pushed onto the undo stack. When the user presses the undo button we do three things:

  • pop a state from the undo stack
  • call the undo method of the state object
  • push the state onto the redo stack

Through the magic of closures, the internal state is encapsulated (that is, the startPoint, endPoint, and objId are not accessible to those who can access the state object).

[1] Or if you like talking in the language of design patterns, you may know this as the memento pattern.

allowed HTML: a, blockquote, ul, ol, li, dl, dt, dd, b, i, strong, em, code, abbr, acronym, sub, sup, span, pre

allowed HTML: a, blockquote, ul, ol, li, dl, dt, dd, b, i, strong, em, code, abbr, acronym, sub, sup, span, pre