is there an opportunity to undo the execution of the last called function. For example I click a
<nav><a href="foo">...</a></nav>
It has an onclick-listener, something like that:
$(function() {
$('nav a').on('click', function() {
$('nav a').removeClass('active');
$(this).addClass('active');
$($(this).attr('href')).addClass('active');
return false;
});
});
I am looking for something with that I can undo the execution of the last function. Any suggestion? Thx!!! :)
Use command pattern, i.e.
Command objects are useful for implementing multi-level undo - if all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method.
The basic JavaScript implementation can look like this:
function command(instance) {
this.command = instance;
this.done = [];
this.execute = function execute() {
this.command.execute();
this.done.push(this.command);
};
this.undo = function undo() {
var command = this.done.pop();
command.undo();
};
}
To test this, construct simple DOM:
<ul>
<li>first</li>
</ul>
and define a command object, you want to use. Such an object should contain its execution logic along with additional behavior for reconstructing previous state of your DOM (in our sample case at least):
var appendcommand = new command({
execute: function(){
$('ul').append('<li>new</li>');
},
undo: function(){
$('ul li:last').remove();
}
});
After executing:
appendcommand.execute();
your page will change from
to
while the execution of:
appendcommand.undo();
will transform this page to its original state:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With