Use a command template , i.e.
Command objects are useful for implementing multi-level cancellation - if all user actions in the program are implemented as command objects, the program can store a stack of the last executed commands. When the user wants to cancel the command, the program simply retrieves the most recent command object and executes its undo () method.
A basic JavaScript implementation might look like this:
function command(instance) { this.command = instance; this.done = []; this.execute = function execute() { this.command.execute(); this.done.push(this.command); }; this.undo = function undo() { var command = this.done.pop(); command.undo(); }; }
To verify this, create a simple DOM:
<ul> <li>first</li> </ul>
and define the command object you want to use. Such an object should contain execution logic along with additional behavior to restore the previous state of your DOM (at least in our example):
var appendcommand = new command({ execute: function(){ $('ul').append('<li>new</li>'); }, undo: function(){ $('ul li:last').remove(); } });
After execution:
appendcommand.execute();
your page will change from
in
at execution:
appendcommand.undo();
converts this page to its original state:
source share