Skip to content

Instantly share code, notes, and snippets.

@Tomalak
Created August 29, 2014 16:36
Show Gist options
  • Save Tomalak/e5e754ffdcf7e9dfa4f9 to your computer and use it in GitHub Desktop.
Save Tomalak/e5e754ffdcf7e9dfa4f9 to your computer and use it in GitHub Desktop.
A "multi-level undo" extender for Knockout observables.
ko.extenders.undoBuffer = function (target, maxUndo) {
var undoBuffer = ko.observableArray([]), undoing;
target.canUndo = ko.computed(function () {
return undoBuffer().length > 0;
});
target.undo = function () {
if (!target.canUndo()) return;
undoing = true;
target(undoBuffer.pop());
undoing = false;
};
target.subscribe(function (oldValue) {
if (undoing) return;
if (undoBuffer().length === maxUndo) undoBuffer.shift();
undoBuffer.push(oldValue);
}, null, "beforeChange");
return target;
};
// usage:
this.fooValue = ko.observable().extend({undoBuffer: 10});
// bindings:
// <input data-bind="value: fooValue">
// <button click: fooValue.undo, enable: fooValue.canUndo">Undo</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment