Skip to content

Instantly share code, notes, and snippets.

@tsmsogn
Created December 19, 2012 06:44
Show Gist options
  • Select an option

  • Save tsmsogn/4334886 to your computer and use it in GitHub Desktop.

Select an option

Save tsmsogn/4334886 to your computer and use it in GitHub Desktop.
JavaScript: UndoManager
this.sample = this.sample || {};
(function () {
/**
*
* @constructor
*/
var UndoManager = function () {
this.initialize();
}, p = UndoManager.prototype;
/**
*
*/
p.initialize = function () {
this.didCommands = [];
this.undidCommands = [];
};
/**
*
* @return {Boolean}
*/
p.canUndo = function () {
return Boolean(this.didCommands.length > 0);
};
/**
*
* @return {Boolean}
*/
p.canRedo = function () {
return Boolean(this.undidCommands.length > 0);
};
/**
*
* @param command
*/
p.push = function (command) {
this.didCommands.push(command);
// @TODO
this.undidCommands = [];
};
/**
*
*/
p.undo = function () {
if (this.canUndo()) {
var command = this.didCommands.pop();
this.undidCommands.push(command);
if (typeof command.unexecute === 'function') {
command.unexecute();
}
}
};
/**
*
*/
p.redo = function () {
if (this.canUndo()) {
var command = this.undidCommands.pop();
this.didCommands.push(command);
if (typeof command.execute === 'function') {
command.execute();
}
}
};
sample.UndoManager = UndoManager;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment