Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo last executed function with jquery

Tags:

undo

jquery

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!!! :)

like image 664
user1800141 Avatar asked Dec 12 '22 20:12

user1800141


1 Answers

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

  • first

to

  • first
  • new

while the execution of:

appendcommand.undo();

will transform this page to its original state:

  • first
like image 138
jwaliszko Avatar answered Dec 28 '22 07:12

jwaliszko