Implementing Undo and Redo functionality javascript and php

14,429

Solution 1

At a basic level, you need two things:

  • an operation stack (array) which keeps track of the operations that have been performed. When the user performs an operation, you create an object that describes the operation and add it to the array. When the user hits undo, you can remove the last item from the array.

  • each operation type needs a 'save' method and an 'undo' method. This can get tricky as some 'undo' methods are similar to their 'save' method (i.e. to undo a horizontal flip you just do another flip), whereas others do not have such symmetry (i.e. to undo a crop you'd have to store the image data as it was before the crop occurred).

If you want 'redo' functionality, then you'd need a second operation stack. Each time an operation was undone, you'd add it to the end of the redo stack. If the user hits 'Redo', then you move it back to the operation stack again.

It may help to look into the Command pattern (http://en.wikipedia.org/wiki/Command_pattern), as this is often used to implement Undo.

Solution 2

My javascript undo manager uses the command pattern. Basically, for each action you also implement an undo action and a redo action. You could build the same functionality serverside.

https://github.com/ArthurClemens/Javascript-Undo-Manager

And this is a clear code example of the command pattern: https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/command.html

Share:
14,429
hashmi
Author by

hashmi

Updated on June 05, 2022

Comments

  • hashmi
    hashmi almost 2 years

    I want to implement Undo and Redo functionality not only for client side but for server side as well. For insatnce i have a div containing image and i can rotate resize and rewrite it , All the basic operations for image generation. And all of the operations update databse and image. you can say my image is being regenerated and database is updated after every action.

    Now i need to implement Undo and Redo functionality. I have done some research as well. What i need is the best approach how to implement the required task. I was thinking to maintain each action "log type thing" or handle it with database or with javascript arrays including HTML or what else??

    what is the best approach to achieve my goal.

    Thanks,