You ask a rather broad question, or is it a fact that needs to be done:
Create a rollback function in editing forms based on KnockoutJS
The question behind this is this: what is the idiomatic way to do this in KnockoutJS? The answer is no. You need to write something.
The basic idea of โโany solution will be the same: save a copy of the source data before editing so that you can return to it after cancellation.
Here are two good ways to do this:
- Use a library, for example. ko.editables is designed specifically for this purpose.
- Do it yourself. Actually, itโs not so difficult: you save the model after the viewing model during initialization, and then โsaveโ and reuse the initialization method when โcancelingโ.
Here is a 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 issues, I suggest going back to SO with specific questions.
source share