Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo dom changes in JS

I am writing a custom HTML editor. User can edit an entire HTML content and the changes will be updated in DOM. We have an option to undo all the changes.

Logic:

Clone an entire container before making change and apply it again.

Disadvantages:

  1. Storing a huge variable in js memory.

  2. And applying the changes again a dom will repaint everything.

Is there any way to achieve the same?.

like image 615
kannanrbk Avatar asked Feb 25 '15 12:02

kannanrbk


People also ask

How do you undo something in JavaScript?

Before an action is applied, you take a snapshot of the current state and save it into an array. That snapshot is the Memento. If the user wants to undo, you simply pop the last memento and apply it. The program returns to the state it was before the last action was applied.

How do you know if Dom has changed?

Show activity on this post. observeDOMChange(document. querySelector('#dom-changes-here')) . subscribe(val => log('DOM-change detected'));

Can JavaScript modify Dom?

The DOM stands for Document Object Model. It can simply be understood as a tree of nodes created by the browser. Each of these nodes has its own properties and methods which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the most unique and useful abilities of JavaScript.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").


1 Answers

Your question is very useful. I don’t know what’s the optimal way of handling this situation, but I do know that there is Command Design Pattern that could work in this case. With Command Design Pattern you can undo events that have been saved in your program. To my understanding the trick to use Command Design Pattern is that you need to have functions that do the opposite thing when you need to undo something. For example if you need to undo add function result, you need to have subtract function. For draw function you need to have clear/erase function. Here is JavaScript example.

like image 78
jyrkim Avatar answered Sep 29 '22 22:09

jyrkim