Revert to first time load value from ajax on cancel

时间:2015-09-14 16:14:28

标签: javascript jquery ajax knockout.js

Basically I have a display view (using span) and edit view (using input) in same page, where only display or edit view is visible to the user at one time.

Display View -> Edit Button
Edit View -> Save Button / Cancel Button

When the user click cancel button, the page will change from edit view to display view with data loaded from ajax call.

My question is:
How to preserve the first loaded ajax call value and retrieve it back when cancel button is click.

Condition:
1) No calling ajax again to fetch back the value
2) The solution should be generic and good enough to be reusable in most similar situation

I believe that this is some how a common problem face by many developer out there.

function MyViewModel() {
  var self = this;
  self.FirstName = ko.observable();
  self.LastName = ko.observable();
  self.SelectedCountryID = ko.observable();
  
  self.GetInformation = function() {
    $.ajax({
      // get data and bind
    });
  }
  
  self.GetCountryInformation = function() {
    $.ajax({
      // get country data and bind to select option
    });
  }
 
  self.SaveInformation = function() {
    $.ajax({
      // post data
   });
  }
  
  self.OnCancelClick = function() {
    // cancel and revert back to first time load vale.
  }
  
  self.GetInformation();
  self.GetCountryInformation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
   <!-- Display View -->
</div>

<div>
  <input type="text" data-bind="value:FirstName">
  <input type="text" data-bind="value:LastName">
  <select data-bind="options: AvailableCountries,
                       optionsText: 'CountryName',
                       value: SelectedCountryID,
                       optionsCaption: 'Choose...'"></select>
 <!-- All other input -->
</div>

1 个答案:

答案 0 :(得分:0)

有两个独立的可观察者。在保存时,将edit observable复制到已保存的observable。取消后,你不会。

&#13;
&#13;
var vm = (function() {
  var self = {
    mode: ko.observable('Display'),
    savedValue: ko.observable(),
    newValue: ko.observable(),
    save: function (data) {
      console.debug("Save", data, self.newValue());
      self.savedValue(self.newValue());
      self.mode('Display');
    }
  };
  
  return self;
}())

ko.applyBindings(vm);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="visible:mode() == 'Display'">
  <span data-bind="text:savedValue"></span>
  <button data-bind="click:mode.bind(null, 'Edit')">Edit</button>
</div>
<div data-bind="visible:mode() == 'Edit'">
  <input data-bind="value:newValue" />
  <button data-bind="click:save">Save</button>
  <button data-bind="click:mode.bind(null, 'Display')">Cancel</button>
</div>
&#13;
&#13;
&#13;