Last Updated: January 02, 2017
·
12.33K
· 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/

CommandManager.execute({
  execute: function(){
    // do something
  },
  unexecute: function(){
    // undo something
  }
});

//call unexecute of prev. command
CommandManager.undo(); 
//call execute of prev. command
CommandManager.redo(); 

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){
  cmd2.execute();
  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);

over 1 year ago ·