rdzera
Last Updated: January 02, 2017
·
6.982K
· alexanderbrevig
Feb007acc38e70d57f7b4c205f7e8b26

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(); 
Say Thanks
Respond

1 Response
Add your response

28430

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);

8 months ago ·
Awesome Job

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