我在我的项目中将 knockout.js 从 1.2 升级到 2.1。我正在使用一些基本模板,它们似乎被破坏了。我包括 jQuery.tmpl.js 和 knockout-2.1.0.js。希望得到一个快速的答复。
<ul data-bind="template: {name:'addressesTemplate', foreach:addresses}"></ul>
<button data-bind="click: addAddress">Add Address</button>
<button data-bind="click: save">Save Account</button>
<script id="addressesTemplate" type="text/html">
<li>
Address Type: <input data-bind="value: addressType"/><br/>
Address Line 1: <input data-bind="value: addressLine1"/><br/>
Address Line 2: <input data-bind="value: addressLine2"/><br/>
City: <input data-bind="value: city"/><br/>
State: <input data-bind="value: state"/><br/>
Country: <input data-bind="value: country"/><br/>
Zip Code: <input data-bind="value: zipCode"/><br/>
<button data-bind="click: remove">Remove</button>
</li>
</script>
<script type="text/javascript">
function addressModel(id) {
return {
id: id,
addressType: ko.observable(),
addressLine1: ko.observable(),
addressLine2: ko.observable(),
city: ko.observableArray(),
state: ko.observableArray(),
country: ko.observableArray(),
zipCode: ko.observableArray(),
remove: function () {
viewModel.addresses.remove(this);
}
};
}
var viewModel = {
id : 0,
username: ko.observable(""),
addresses: ko.observableArray([]),
addAddress: function () {
this.addresses.push(new addressModel(""));
},
save: function () {
alert(ko.toJSON(this));
$.ajax({
url: "/account/Save",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function(result) {alert(result.message) },
failure: function(result) { alert('fail') }
});
}
};
ko.applyBindings(viewModel);
</script>