what is the best way to reset knockout viewmodel back to the original data?
if the original data json is not changed, after I do some changed on the observable, how can I set it back? just like refresh the page.
I think it is bad practice to "refresh" your viewModel. You could refresh it like this:
ko.cleanNode(document.getElementById("element-id"));
ko.applyBindings(yourViewModel, document.getElementById("element-id"));
But I think it is cleaner to have a method on your view model called "reset", that sets your observables back to initial states. Maybe like this:
function MyViewModel() {
this.something = ko.observable("default value");
this.somethingElse = ko.observable(0):
this.reset = function() {
this.something("default value");
this.somethingElse(0);
}
}
ViewModels often get constructed with some data supplied by some dto. Resetting a viewmodel to its original state can be done by
function Car(dto) {
var originalState = dto;
this.brand = ko.observable();
this.color = ko.observable();
this.reset = function() {
this.brand(originalState.brand);
this.color(originalState.color);
}
this.reset();
}
ko.applyBindings(new Car({
brand: 'mercedes',
color: 'red'
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>
<em>Current viewmodel values:</em>
<br/>Brand: <strong data-bind="text:brand"></strong>
<br/>Color: <strong data-bind="text:color"></strong>
</p>
<p>
<em>Change viewmodel values:</em>
<br/>Brand:
<input data-bind="textInput:brand">
<br/>Color:
<input data-bind="textInput:color">
</p>
<p>
<button data-bind="click: reset">Reset viewmodel values</button>
</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With