Created
June 15, 2013 12:52
-
-
Save hanigamal/5788033 to your computer and use it in GitHub Desktop.
Pure JS undo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
/** | |
* @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