Skip to content

Knockout.Undoable

Areson edited this page Jul 12, 2012 · 5 revisions

Provides a basic undo stack for observables. All changes made to the observable are recorded and can be rolled back to any point. An optional value can be included to limit the size of the undo stack.

Example

var observable("foo").extend({undoable: true});

observable("bar");
observable(42);

//The observable is again "bar"
observable.undo();
//The observable is again "foo"
observable.undo();

The undo method can also be called using an index, which represents location of the item on the undo stack to roll back to. Note that rolling back to any state other than the last one on the undo stack will remove all states after that state.

The undo stack is accessible via the undoStack. The undo stack is implemented as an observable, so changes to it can be tracked. This can be used to create a visual "history" of the observable. If a value from the undo stack is passed to undo then the observable is rolled back to that state. Each item on the undo stack also has a isCurrentUndoState which returns TRUE if the state equal to the current state of the observable.

The undo stack can be cleared by calling clearUndoStack, and the maximum size of the stack can be set by passing the stackSize option when adding the undoable extender:

var observable = ko.observable(42).extend({undoable: {stackSize: 5}});

When a stack size greater than 0 is specified, the undo stack will be kept to that size by removing the oldest undo states from the stack.

A more detailed example can be seen here: http://jsfiddle.net/Areson/FSaYZ/

For an example showing use with an ObservableArray, go here: http://jsfiddle.net/Areson/urjGW/

Clone this wiki locally