Jsonary Undo/Redo Plugin
- jsonary.js - the core Jsonary library
- plain.jsonary.js - a default set of renderers, that look similar to plain JSON
- plain.jsonary.css - the stylesheet used by the above renderers
- jsonary.undo.js - the undo/redo plugin
How it works
Internally, Jsonary uses the "JSON Patch" format to communicate changes to the data. When a change listener is registered, and data changes are made, the listener is passed an object representing the JSON Patch that was applied, along with the document it was applied to.
So to obtain an "undo history", we simply have to collect these patch/document pairs.
Jsonary.registerChangeListener(function (patch, document) { undoList.push({patch: patch, document: document}); });
We can then create a method Jsonary.undo()
that pops off the latest change from this list, reverses it, and applies the resulting patch to the appropriate document.
Jsonary.extend({ undo: function () { var lastChange = undoList.pop(); if (lastChange != undefined) { lastChange.document.patch(lastChange.patch.inverse()); } } });
Actually, the full code is slightly more complicated than that, because when the patch is applied, the change listener callback is called again. It also maintains a "redo" list.
However, it is still extremely short: have a look!
Working example
Try editing this item, and then pressing CTRL+Z, CTRL+SHIFT+Z or CTRL+Y (Mac users should be able to use CMD instead).