CRUD using Knockout no mapping plugin
by douglasloyo
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<h2>Form for adding and updating a person.</h2>
<form data-bind="submit: save">
<input type="hidden" data-bind="value: SelectedPerson().id" />
<p>First Name: <input id="personFirstName" type="text" data-bind="value: SelectedPerson().firstName" /></p>
<p>Last Name: <input type="text" data-bind="value: SelectedPerson().lastName" /></p>
<p><input type="submit" value="Add/Save" /></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 person(data)
{
this.id = ko.observable(data.id);
this.firstName = ko.observable(data.firstName);
this.lastName = ko.observable(data.lastName);
}
function viewModel(){
var self = this;
//List of People
self.People = ko.observableArray([]);
self.SelectedPerson = ko.observable(new person({id:0,firstName:"",lastName:""}));
self.EmptyPersonModel = ko.observable(new person({id:0,firstName:"",lastName:""}));
//Push some fake data so it makes sense.
self.People.push(new person({id:1,firstName:"John",lastName:"Doe"}));
self.People.push(new person({id:2,firstName:"Mary",lastName:"Jane"}));
//Other functions:
//Initiate an edit.
self.startEdit = function(item){
self.SelectedPerson(item);
focusOnForm();
};
//Save.
self.save = function(){
//Is this a new object?
if(self.SelectedPerson().id()<=0){
//Persist to Db.
self.SelectedPerson().id(self.getId());
self.People.push(new person( { id:self.SelectedPerson().id(),
firstName:self.SelectedPerson().firstName(),
lastName:self.SelectedPerson().lastName() }));
}
//Or are we editing?
else{
//Persist to Db.
alert("edit");
}
//Whatever we did lets clean the form with empty
var emptyTemplate = ko.observable(new person({id:0,firstName:"",lastName:""}));
self.SelectedPerson(emptyTemplate());
focusOnForm();
};
//Delete
self.deleteItem = function(item){
if(confirm("Are you sure?"))
self.People.remove(item);
focusOnForm();
};
//Temp to have ids. This should be repalced by a REST api persistance call.
self.getId = function(){
return self.People().length+1;
}
}
var vm =...