Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout reset viewmodel to original data

Tags:

knockout.js

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.

like image 578
hysyzq Avatar asked Oct 13 '16 05:10

hysyzq


2 Answers

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);
  }
}
like image 67
henrikmerlander Avatar answered Oct 17 '22 18:10

henrikmerlander


ViewModels often get constructed with some data supplied by some dto. Resetting a viewmodel to its original state can be done by

  1. keeping track of the original state in a private variable.
  2. 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>
like image 27
Philip Bijker Avatar answered Oct 17 '22 16:10

Philip Bijker