Knockout reset viewmodel to source data

What is the best way to reset the knockout viewmodel back to the original data?

if the json source data is not changed, after some changes have changed on the observable, how can I set it back? same as refreshing a page.

+4
source share
2 answers

I think it is bad practice to “update” your viewModel. You can update it as follows:

ko.cleanNode(document.getElementById("element-id"));
ko.applyBindings(yourViewModel, document.getElementById("element-id"));

But I think that for a model of your kind called "reset", a cleaner method that returns your observables to their original 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
source

ViewModels , dto.

  • .
  • reset, , 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>
Hide result
0

Source: https://habr.com/ru/post/1657580/


All Articles