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:
Storing a huge variable in js memory.
And applying the changes again a dom will repaint everything.
Is there any way to achieve the same?.
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:
Storing a huge variable in js memory.
And applying the changes again a dom will repaint everything.
Is there any way to achieve the same?.
Share Improve this question asked Feb 25, 2015 at 12:56 kannanrbkkannanrbk 7,14413 gold badges58 silver badges96 bronze badges 5-
2
as you are using jquery, why not store the cloned dom as a string, then use
.html()
to reinsert. that way you are only storing strings rather then dom fragments. – atmd Commented Feb 25, 2015 at 13:00 - storing html strings isn't memory intensive and is most likely what you would send to server anyway – charlietfl Commented Feb 25, 2015 at 13:03
- contentEditable pages support undo mands, but I don't know how good the browser support for that is – the8472 Commented Feb 25, 2015 at 13:07
- @atmd Is it okay to store a huge html string in js? – kannanrbk Commented Feb 25, 2015 at 13:43
- it's less intensive then storage huge objects, plus I'd argue easier to transport (save to a db via ajax post etc) – atmd Commented Feb 25, 2015 at 13:54
3 Answers
Reset to default 5Your 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.
You could try using some pression in order to reduce the amount of memory:
- http://pieroxy/blog/pages/lz-string/index.html
- http://code.google./p/jslzjb/
- String pression in JavaScript
Use the web storage to keep the DOM history.
Imagine you want to undo the last three actions executed. You shouldn't save it in memory because you can lose information on a page refresh. And you really don't know if this action will be used to save in memory.
You can use the web storage with data pression to keep the smallest amount of data.