How to cancel/revert changes to an observable model (or replace model in array with untouched copy)

前端 未结 5 1966
萌比男神i
萌比男神i 2021-01-01 12:19

I have a viewModel with an observableArray of objects with observable variables.

My template shows the data with an edit button that hides the display elements and s

5条回答
  •  清歌不尽
    2021-01-01 12:39

    Very old question, but I just did something very similar and found a very simple, quick, and effective way to do this using the mapping plugin.

    Background; I am editing a list of KO objects bound using a foreach. Each object is set to be in edit mode using a simple observable, which tells the view to display labels or inputs.

    The functions are designed to be used in the click binding for each foreach item.

    Then, the edit / save / cancel is simply:

    this.edit = function(model, e)
    {
        model.__undo = ko.mapping.toJS(model);
        model._IsEditing(true);
    };
    
    this.cancel = function(model, e)
    {
        // Assumes you have variable _mapping in scope that contains any 
        // advanced mapping rules (this is optional)
        ko.mapping.fromJS(model.__undo, _mapping, model);
        model._IsEditing(false);
    };
    
    this.save = function(model, e)
    {
        $.ajax({
            url: YOUR_SAVE_URL,
            dataType: 'json',
            type: 'POST',
            data: ko.mapping.toJSON(model),
            success: 
                function(data, status, jqxhr)
                {
                    model._IsEditing(false);
                }
        }); 
    };
    

    This is very useful when editing lists of simple objects, although in most cases I find myself having a list containing lightweight objects, then loading a full detail model for the actual editing, so this problem does not arise.

    You could add saveUndo / restoreUndo methods to the model if you don't like tacking the __undo property on like that, but personally I think this way is clearer as well as being a lot less code and usable on any model, even one without an explicit declaration.

提交回复
热议问题