How to implement an undo and redo system in javascript?


I see in some native tools in javascript , the redo and undo option, as if it were a Ctrl + z and Ctrl + y , but they are graphical tools and not forms.

I thought of something like…

  1. Components will be estáticos .
  2. Each component will have its own dynamically generated code.
  3. Each action will have a start value and an end value, this data will be stored in an objeto to undo along with the component code.
  4. When pressing Ctrl + Z the last element is removed from the undo objeto and placed in another one responsible for restoring, and when moving its initial value it is replaced by the final one and compiled in the component with angular and vice versa.

I did some tests and it is totally possible to do this, but the work will be huge, as everything is created dynamically. Is there any other way to implement this? using cache or some library? I didn't find anything related on the internet.


I found this library on GitHub that makes the undo and redo approach easier. You only need to say which methods are responsible for creating and removing the components (both graphics, characters, etc). Everything is stored on a stack and then you just call the UndoManager class methods to perform the operations: undoManager.undo(); and undoManager.redo(); . It might be useful for you.

var undoManager = new UndoManager(),
people = {},

addPerson = function(id, name) {
    people[id] = name;

removePerson = function(id) {
    delete people[id];

createPerson = function (id, name) {
    // first creation
    addPerson(id, name);

    // make undo-able
        undo: function() {
    redo: function() {
        addPerson(id, name);

createPerson(101, "John");
createPerson(102, "Mary");

console.log("people", people); // {101: "John", 102: "Mary"}

console.log("people", people); // {101: "John"}

console.log("people", people); // {}

console.log("people", people); // {101: "John"}

Here you can test the library working.

Scroll to Top