Created
August 29, 2014 16:36
-
-
Save Tomalak/e5e754ffdcf7e9dfa4f9 to your computer and use it in GitHub Desktop.
A "multi-level undo" extender for Knockout observables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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