0

I've ran in to an issue lately where as I thought it would be fairly easy to fix but ran in to problems.

I am using Knockout and MVC where I have a form where users can enter data and they have an option of either submitting the changes that they have made or cancel.

The problem comes when they want to cancel, the changes still get changed, since it binds automatically to the observable. What i want to do is to revert to the old model, before they changed.

 me.contactEditCancel = function() {
        me.Contact= oldContact;
    }

Where the oldContact is assigned when the edit form is opened.

I cant get it to loose its depedencies tracking... Any idea what to do? To copy the observableArray without the tracking, so I dont have to reload the entire page to get the old model back.

Hopefully my question was clear enough, appreciate any help!

Marcus
  • 1
  • 2
  • a [jsfiddle](http://jsfiddle.net) with some more code and bindings will help. – Dandy Oct 04 '15 at 17:55
  • The new values should be bound to separate variables and then copied when they submit. – Roy J Oct 04 '15 at 19:35
  • I am working with ko.mapping.FromJS so it is only model/object bound, I somehow then need to bind the variables created to the model? Any idea? – Marcus Oct 04 '15 at 19:43
  • See also: http://stackoverflow.com/questions/5874860/knockoutjs-how-to-cancel-revert-changes-to-an-observable-model-or-replace-mode – Roy J Oct 04 '15 at 19:47
  • Your question contains too little code to be able to help you. Please edit the question and add an [mcve]. – Jeroen Oct 04 '15 at 20:23
  • Perhaps this will help: http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html – Michael Best Oct 05 '15 at 21:45

1 Answers1

0

You need to work with original values and edit values, which is a copy of original values. When users submit, you save the edit values. If they cancel, you show the original values.

I don't know about your UI patterns, but I often have a grid of data with Edit buttons. Click one, and you're editing that item in a popup. This is roughly the pattern I use for managing that:

self.itemInEdit = ko.observable(null);
self.edit = function(item) {
    self.itemInEdit(new MyViewModel(ko.toJS(item)));
};
self.cancel = function () {
    self.itemInEdit(null);
};
self.submit = function() {
    // Save self.itemInEdit
};
Joe Wilson
  • 5,591
  • 2
  • 27
  • 38