-
-
Save krishna19/65cdf82633a23d6280b2e6818e0b0d5b to your computer and use it in GitHub Desktop.
Easy undo-redo in JavaScript.
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
function UndoItem (perform, data) { | |
this.perform = perform; | |
this.data = data; | |
} | |
/** | |
* UndoStack: | |
* Easy undo-redo in JavaScript. | |
**/ | |
function UndoStack(self) { | |
this.stack = []; | |
this.current = -1; | |
this.self = self; | |
} | |
/** | |
* UndoStack#push (action, data); | |
* perform(true, data) -> Function which performs redo based on previous state | |
* perform(false, data) -> Function which performs undo based on current state | |
* data -> Argument passed to undo/redo functions | |
**/ | |
UndoStack.prototype.push = function (perform, data) { | |
this.current++; | |
// We need to invalidate all undo items after this new one | |
// or people are going to be very confused. | |
this.stack.splice(this.current); | |
this.stack.push(new UndoItem(perform, data)); | |
}; | |
UndoStack.prototype.undo = function () { | |
var item; | |
if (this.current >= 0) { | |
item = this.stack[this.current]; | |
item.perform.call(this.self, false, item.data); | |
this.current--; | |
} else { | |
throw new Error("Already at oldest change"); | |
} | |
}; | |
UndoStack.prototype.redo = function () { | |
var item; | |
item = this.stack[this.current + 1]; | |
if (item) { | |
item.perform.call(this.self, true, item.data); | |
this.current++; | |
} else { | |
throw new Error("Already at newest change"); | |
} | |
}; | |
UndoStack.prototype.invalidateAll = function () { | |
this.stack = []; | |
this.current = -1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment