Make copy of Object for undo function
-
Hey guys,
I have now tried for hours (no kidding) to implement an undo function in my app - but I can’t figure out how to correctly implement this. I guess I run into a problem regarding asynchronious/synchronious code execution.
I have an object I like to copy before I delete an element. So in case the user like to undo the last action I can simply “restore” the copy of the original object.
But whatever combination I have tried the respective element is also deleted in the copy.Before I delete an element in the object this.Survey I make a copy:
methods: { storeUndoMemory() { this.SurveyUndoMemory = Object.assign({}, this.Survey); }, deleteQuestion(val, val2) { this.storeUndoMemory(); this.$delete(this.Survey.Pages[val].Questions, val2); this.UndoLastStepNotify(); }, cloneObject(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; }
Instead of using Object.assign() I also tried the function cloneObject() as I thought that the problem occurs cause Object.assign does not make a copy but only is a kind of reference in the original object. But it makes no difference.
-
@dirkhd I would us something more Vue specific, for example Vuex. Here is a Vuex plugin for undo/redo functionality:
https://github.com/anthonygore/vuex-undo-redo
There is an article about it from the author:
https://vuejsdevelopers.com/2017/11/13/vue-js-vuex-undo-redo/?jsdojo_id=hn_vur
Regarding object.copy, I think in your situation I would just use some solution from this thread:
If speed is not your concern, then this snippet is the safest way to deep clone js objects:
newObj = JSON.parse(JSON.stringify(oldObj))
-
@dirkhd check v-mutation https://quasar.dev/vue-directives/mutation#Undo-redo-example
-
Thx a lot for all your ideas.
I really do not understand why after all my approaches
newObj = JSON.parse(JSON.stringify(oldObj))
actually works
For the long run, I will then implement a better solution based on Vuex / mutations.
-
@dirkhd said in Make copy of Object for undo function:
I really do not understand why after all my approaches
Please do not stop digging, searching, testing, learning until you WILL understand this “why” completely. The “why” is the most important. Everywhere. You have an excellent opportunity to take your undestanding of Vue, reactivity and programming to the next level.