Being able to undo and redo actions is awesome! I already knew the command pattern, but as always everything is different in JavaScript. After figuring it out I want to share how it works.
Very short theory
The idea behind the command pattern is to sort of “thingify” actions. Instead of adding countless methods to objects, countless command classes are made. These can be passed to a subjects execute method. With “subject” I mean the object, that actually performs the command. If a subject keeps track of the commands which are passed it’s execute method, a history is created. This makes it possible to add undo and redo methods to those objects.
This complete changes the way I normally code. But I like it! I’m building my own JS game engine in my spare time, so tackling the command pattern is super helpful for that.
Example
Enough theory, lets get our hands dirty!
The supertype command class
To keep the commands short, readable and maintainable, I created a supertype called Command.
More concrete commands will inherit this, but that comes later.
Subjects
Next we need something for performing commands. In my example I create one subject called Mountaineer, because I like mountaineers. Those brave people deserve a JS Class! Instances of mountaineers will keep track of their commands by themselves, so every mountaineer can undo and redo independently. The following example is already complete, containing the needed methods called execute, undo and redo.
Of course, many more and different kinds of subjects can be created, but I want to keep this article short.
Actions
Because commands could actually contain more than one and also combinations of actions, I create the actions separately. The mountaineer will be able to climb and fall.
Concrete commands
Finally the actual commands! They are really small and super easy to read. All what happens here is choosing the actions for the command. In these cases one action for both the normal and the undo function.
As imagination is limitless, commands are too.
Showing of the undo and redo magic
That is all. It is really that simple! Let us see it in action.
Performance issues
Creating many instances of commands could become a serious memory issue! In that case, simply limiting the subjects _commandsList should do the trick. A lot of desktop applications (used to) do exactly that.
Found a mistake? Have a question or suggestion?
I love feedback! Please contact me at https://twitter.com/KimHogeling