Nicola Cassolato
Nicola Cassolato

Reputation: 193

Knockout: editing data with easy rollback to previous value

There are many blog posts and discussions about editing data in Knockout. The main problem I have is that you need an easy way to revert your data to the previous value when the user cancel an editing operation (or when an Ajax call goes wrong).

I was not satisfied with the examples I found: I needed something VERY simply even when editing very complex models.

Upvotes: 3

Views: 2138

Answers (3)

Matt Wilson
Matt Wilson

Reputation: 8319

Ryan Niemeyer's "Getting the Most Out of Knockout.js" screencast includes a nice way to do this (along with a load of other useful tips) - I recommend checking it out.

http://vimeo.com/51103092

He talks about reverting at about 16:30.

Upvotes: 1

photo_tom
photo_tom

Reputation: 7342

I agree with Nicola's answer in that approach is the most popular approach.

I've used this http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html which is a fairly polished way to do this. It has worked well in my apps.

Upvotes: 1

Nicola Cassolato
Nicola Cassolato

Reputation: 193

This is the solution I found, I'm sharing it in order to understand possible drawbacks from someone more expert than me, and of course to help.

When an "edit" button is clicked, I create a copy of the data being edited.

Edit button (ie: on each row of a table with a foreach binding)

<button data-bind="click: editItem">Edit</button>

From my ViewModel:

this.selectedItem = ko.observable();
this.selectedItemCache = ko.observable();
this.editItem = function (item) {
    self.selectedItem (item);
    self.selectedItemCache (ko.mapping.toJS(item)); // ko.mapping.toJS "detach" my item from the view model
}

When the user click on the "cancel" button or when the AJAX call used to update the server fails, I copy the data from the "cache" observable with:

this.cancelEditItem = function () {
    for (var prop in self.selectedItem) {
        if (typeof self.selectedItem[prop] === 'function') {
            self.selectedItem[prop](self.selectedItemCache()[prop]);
        }
    }
}

Upvotes: 2

Related Questions