How to implement a system of undo and redo in javascript?

3

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

I thought of something like ...

  • The components will be estáticos .
  • Each component will have its own dynamically generated code.
  • Each action will have an initial value and a final value, this data will be stored in a objeto to undo along with the component code.
  • When firing Ctrl + Z the last element is removed from the objeto of undo and placed on another responsible for restoring, and moving its initial value is changed at the end and compiled into the component with angular and vise versa.
  • I've done a few tests and it's totally possible to do this, however the work will be giant because everything is created dynamically. Is there any other way to implement this? using cache or any library? I did not find anything related on the internet.

        
    asked by anonymous 15.08.2017 / 15:56

    1 answer

    2

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

    var undoManager = new UndoManager(),
    people = {},
    addPerson,
    removePerson,
    createPerson;        
    
    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
        undoManager.add({
            undo: function() {
            removePerson(id)
        },
        redo: function() {
            addPerson(id, name);
            }
        });
    }
    
    createPerson(101, "John");
    createPerson(102, "Mary");
    
    console.log("people", people); // {101: "John", 102: "Mary"}
    
    undoManager.undo();
    console.log("people", people); // {101: "John"}
    
    undoManager.undo();
    console.log("people", people); // {}
    
    undoManager.redo();
    console.log("people", people); // {101: "John"}
    

    Here you can test the library working.

        
    15.08.2017 / 16:45