What is wrong with my object(regarding knockoutjs mapping plugin)
http://stackoverflow.com/questions/8000686/what-is-wrong-with-my-objectregarding-knockoutjs-mapping-plugin
by mrrodd
HTML
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<script src="https://rawgithub.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<div id="customerDiv" >
<form action="/update/all/customers" method="POST">
<p>
You have <span data-bind="text: customers().length"> </span> customer(s)
</p>
<table data-bind="visible: customers().length > 0">
<thead>
<tr>
<th></th>
<th>Customer Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Sales Rep</th>
<th></th>
</tr>
</thead>
<tbody data-bind='template: { name: "customerRowTemplate", foreach: customers }'></tbody>
</table>
<button class="btn primary" data-bind="click: addCustomer">
Add Customer
</button>
<a href="#" class="btn" data-bind="click: function() { viewModel.saveCustomers() }" > Save </a>
</form>
</div>
<script type="text/html" id="customerRowTemplate">
<tr >
<td><a data-bind="visible : id > 0, attr: { href : '/m100/' + id + '/' + name }" class="btn success">Go</a></td>
<td><input class="required span2" data-bind="value: name"/></td>
<td><input class="span2" data-bind="value: address"/></td>
<td><input class="span2" data-bind="value: city"/></td>
<td><input class="span2" data-bind="value: state"/></td>
<td><input class="span2" /></td>
<td><a href="#" class="btn danger" data-bind="visible : id() > 0, click: function() { viewModel.removeCustomer($data) }">Delete</a></td>
</tr>
</script>
JavaScript
$(function() {
$("input").live('change', function() {
$(this).css('background-color', '#ccffcc');
$(this).addClass('changed');
});
});
var viewModel = {
customers: ko.observableArray(),
addCustomer: function() {
this.customers.push({
name: ko.observable("New Customer"),
city: ko.observable(""),
address: ko.observable(""),
state: ko.observable(""),
id: ko.observable("0")
});
},
removeCustomer: function(customer) {
if (confirm("Delete customer?")) {
this.customers.remove(customer);
$.post("/remove/customer", {
id: customer.id
}, function() {
});
}
},
saveCustomers: function() {
var data = ko.utils.stringifyJson(this.customers);
}
};
viewModel.findCustomerById = function(id) {
var lists = this.customers();
for (var i = 0; i < lists.length; i++)
if (lists[i].id === id) return lists[i];
};
//$.getJSON("/json/customers", function(data) {
var data2 = [{
"address": "806",
"city": "Durham",
"id": 1,
"name": "Coke",
"salesRep": "Drew Hamlett",
"state": "NC",
"user": {
"email": "[email protected]",
"id": 4,
"name": "Drew",
"password": "stretch"
}}];
ko.mapping.fromJS(data2, null, viewModel.customers);
//});
ko.applyBindings(viewModel, document.getElementById("customerDiv"));