Last Updated: January 02, 2017
· alexanderbrevig

Command Pattern in JavaScript (undo/redo)

Ever wanted to support undo/redo in your JS app?

I did, so I wrote a CommandManager that supports execution, unexecution and reexecution of commands.

Try the demo: http://alexanderbrevig.github.com/CommandManager.js/examples/

  execute: function(){
    // do something
  unexecute: function(){
    // undo something

//call unexecute of prev. command
//call execute of prev. command
Say Thanks

1 Response
Add your response


Hi Alexander,
I was taking a look at your CommandManager code and I think I found a bug, when you click redo() you're actually pushing once more than you should the last thing that was done.
As you are already pushing the last function on the latest if, in the first if it only should be pushed once to readd the previously removed function with pop:
if (cmd2 === undefined){
cmd2 = CommandManager.executed.pop();
CommandManager.executed.push(cmd2); //needed to add last command removed in previous line
//Removed line: CommandManager.executed.push(cmd2);

if (cmd2 !== undefined){
  CommandManager.executed.push(cmd2); //this adds the executed command as usual

Also in this case may look too much but I would replace the content inside of the latest if with: this.execute(cmd2);

8 months ago ·
Awesome Job

96b73d3e 7dde 11e7 8947 789166ad48cb
Sr. Computer Scientist
San Jose or San Francisco, Californ
Full Time