问题
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.
回答1:
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);
}
}
回答2:
ViewModels often get constructed with some data supplied by some dto. Resetting a viewmodel to its original state can be done by
- keeping track of the original state in a private variable.
- adding a reset function which can be called at construction time as well as when needing to reset.
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>
来源:https://stackoverflow.com/questions/40012920/knockout-reset-viewmodel-to-original-data