Skip to content

Instantly share code, notes, and snippets.

@hanigamal
Created June 15, 2013 12:52
Show Gist options
  • Save hanigamal/5788033 to your computer and use it in GitHub Desktop.
Save hanigamal/5788033 to your computer and use it in GitHub Desktop.
Pure JS undo
/*
/**
* @constructor
*/
Commands = function() {
this.undoStack = [];
this.redoStack = [];
};
/**
* Executes an action and adds it to the undo stack.
* @param {function()} action Action function.
* @param {function()} reverse Reverse function.
* @param {Object=} ctx The 'this' argument for the action/reverse functions.
*/
Commands.prototype.execute = function(action, reverse, ctx) {
this.undoStack.push( {action: action, reverse: reverse, ctx: ctx} );
action.call(ctx);
this.redoStack.length = 0;
};
Commands.prototype.undo = function() {
var c = this.undoStack.pop();
if (c) {
c.reverse.call(c.ctx);
this.redoStack.push(c);
}
};
Commands.prototype.redo = function() {
var c = this.redoStack.pop();
if (c) {
c.action.call(c.ctx);
this.undoStack.push(c);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment