How to implement a javascript undo and redo system?

Asked

Viewed 435 times

3

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

I thought of something like...

  1. The components will be estáticos.
  2. Each component will have its own dynamically generated code.
  3. Each action will have an initial value and a final value, this data will be stored in a objeto to undo together with component code.
  4. By triggering the Ctrl + Z the last element is taken from the objeto to undo and placed in another responsible for restoring, and when moving its initial value is exchanged for the final and compiled into the component with angular and vise versa.

I did some tests and it’s totally possible to do this, but the work will be huge, because everything is created dynamically. Is there any other way to implement this? using cache or some library? I found nothing related on the internet.

1 answer

2


I found this library on Github which facilitates the undoing and redoing approach. You only need to tell which methods are responsible for creating and removing the components (both graphics, characters, etc.). Everything will be stored in a stack and then just call the class methods UndoManager to carry out the operations: undoManager.undo(); and undoManager.redo();. Might be useful to 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 working library.

  • 1

    Thanks for answering, I will test it later and give the feedback, but from what I realized it is for canvas, in my case I will not use canvas

  • 1

    I hope I helped... And I believe that it serves for any object both graphic and diverse components, as shown in the example code (Person). Everything will depend on implementing library methods to suit your components.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.