Reputation: 351
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?
Upvotes: 1
Views: 793
Reputation: 2253
I use this plugin which is great and allows you to rollback your changes, or commit them, etc.
Upvotes: 0
Reputation: 4778
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
Upvotes: 1