Knockout using Mapping CRUD
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<h2>Form for adding and updating a person.</h2>
<form data-bind="submit: save, with: SelectedPerson">
<input type="hidden" data-bind="value: id" />
<p>First Name: <input id="firstName" type="text" data-bind="value: firstName" /></p>
<p>Last Name: <input type="text" data-bind="value: lastName" /></p>
<p><input type="submit" value="Add/Save" /><input type="button" value="Cancel" data-bind="click: cancel" /></p>
</form>
<hr>
<h2>List of people</h2>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: People">
<td data-bind="text: id"/>
<td data-bind="text: firstName"/>
<td data-bind="text: lastName"/>
<td><button data-bind="click: startEdit">Edit</button></td>
<td><button data-bind="click: deleteItem">Delete</button></td>
</tbody>
</table>
JavaScript
function viewModel(){
//Will come from a REST api call.
var emptyDataTemplate = {id:0, firstName:"", lastName:""};
var data = [
{id:1, firstName:"John", lastName:"Doe"},
{id:2, firstName:"Mary", lastName:"Jane"}
];
function EmptyTemplate()
{
return ko.mapping.fromJS(emptyDataTemplate);
}
var self = this;
self.People = ko.mapping.fromJS(data);
self.SelectedPerson = ko.observable(ko.mapping.fromJS(emptyDataTemplate));
self.EditingPerson = ko.observable(ko.mapping.fromJS(emptyDataTemplate));
self.startEdit = function(item){
//Store a copy so that they are not linked and we can cancel out of the edit.
self.EditingPerson(ko.toJS(item));
self.SelectedPerson(item);
};
self.save = function(form){
//If we dont have an Id then its a Add New.
if(self.SelectedPerson().id()<=0){
//Here is where you would access a REST webservice endpoint and you would persist the object.
self.SelectedPerson().id(self.getId());
//Here we are basically copying and creating a new on to add to the list.
//Note if you want all bindings to work the new one also has to be wrapped in observable.
var unmapped = ko.mapping.toJS(self.SelectedPerson());
var remap = ko.mapping.fromJS(unmapped);
//Add the new person object to the array.
self.People.push(remap);
}
else{ //We are editing an existing one.
alert("edit");
}
//Whatever we did lets clean the form with empty
self.SelectedPerson(new EmptyTemplate());
$("#firstName").focus();
};
self.deleteItem = function(item){
if(confirm("Are you sure?"))
self.People.remove(item);
};
//How to cancel out of a edit....???
self.cancel =...