You ask a rather broad question, or it is fact a To Do:
Create rollback functionality on KnockoutJS based edit forms
The question behind that to do is: what is the idiomatic way to do that in KnockoutJS? The answer is: there is none. You need to write something yourself.
The basic idea behind any solution will be the same: save a copy of the original data from before editing so you can revert to it upon canceling.
Here are two good ways to do that:
- Use a library, e.g. ko.editables is designed for exactly this purpose.
- Do It Yourself. It's actually not that hard: you save the model behind the view model upon initialization, and upon "save", and reuse the initialize method on "cancel".
Here's some sample code for the latter:
var dummyItem = { id: 42, name: "John doe" };
function ItemViewModel(data) {
var self = this, currentDto = data;
self.id = ko.observable();
self.name = ko.observable();
self.isInEditMode = ko.observable(false);
self.reset = function() {
self.id(currentDto.id);
self.name(currentDto.name);
self.isInEditMode(false);
};
self.saveState = function() {
currentDto = {
id: self.id(),
name: self.name()
};
self.isInEditMode(false);
};
self.reset();
}
function RootViewModel() {
var self = this;
self.items = ko.observableArray([new ItemViewModel(dummyItem)]);
self.startEdit = function(item) { item.isInEditMode(true); };
self.save = function(item) { item.saveState(); };
self.cancel = function(item) { item.reset(); };
}
ko.applyBindings(new RootViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<ul data-bind="foreach: items">
<li>
<span data-bind="text: id"></span>
<span data-bind="text: name"></span>
<input data-bind="textInput: name, visible: isInEditMode">
<button data-bind="visible: !isInEditMode(), click: $root.startEdit">edit</button>
<button data-bind="visible: isInEditMode, click: $root.save">save</button>
<button data-bind="visible: isInEditMode, click: $root.cancel">cancel</button>
</li>
</ul>
You should probably try to implement one of these two options for your own context. If you run into specific problems, I suggest getting back to SO with specific questions.