1
votes

I have 20 text boxes that are bind with knockout observables.Initially these text boxes are bind with the data from database. When user edits the text box and click on the a reset button the old(the data that is fetched from database) needs to be restored.

Can any one have an idea of how this can be achieved using knockout js?

2

2 Answers

1
votes

First of all create a reset binding, for example

ko.bindingHandlers.resetValue = {
    init: function(element, valueAccessor){
        var attribute = valueAccessor();

        attribute.initialValue = ko.unwrap(attribute);

        attribute.reset = function(){
            if(attribute.isDirty()){
                attribute(attribute.initialValue);
            }            
        };

        attribute.isDirty = ko.computed(function(){
            return attribute.initialValue !== ko.utils.unwrapObservable(attribute);
        });

        ko.applyBindingsToNode(element, {
            click: function(){
                attribute.reset();
            },
            visible: attribute.isDirty            
        });
    }
};

Here's more about Creating custom bindings

Now we're ready to use the resetValue binding

<div>
    <a href="#" data-bind="resetValue: firstName">Reset</a>
    <input data-bind="value: firstName"></input>
</div>
<div>
    <a href="#" data-bind="resetValue: lastName">Reset</a>
    <input data-bind="value: lastName"></input>
</div>

and here is the ViewModel

var ViewModel = function(){
    var self = this;
    self.firstName = ko.observable("First Name");
    self.lastName = ko.observable("Last Name");
};

ko.applyBindings(new ViewModel());

Take a look on the jsfiddle version

0
votes

I use this plugin which is great and allows you to rollback your changes, or commit them, etc.