我有一个名为客户的模型:
function customer(id, name, age, comments) {
var self = this;
self.Id = id;
self.Name = name;
self.Age = age,
self.Comments = comments;
self.addCustomer = function () {
$.ajax({
url: "/api/customer/",
type: 'post',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
//SOMETHINGS WRONG HERE
customerVM();
}
});
}
}
添加客户后,客户列表不会自动更新。在模型中调用 customerVM() 会进入 viewModel 函数,但永远不会进入 getCustomers 函数,所以我一定是错误地调用了 viewModel。这就是我从调试中看到的。
显示列表的函数在 viewModel 中:
function customerVM() {
var self = this;
self.customers = ko.observableArray([]);
self.getCustomers = function () {
self.customers.removeAll();
$.getJSON("/api/customer/", function (data) {
$.each(data, function (key, val) {
self.customers.push(new customer(val.Id, val.Name, val.Age, val.Comments));
});
});
};
}
添加客户后,我需要以某种方式调用 getCustomers 。我该怎么做?
这是客户的html
<table >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Comments</th>
</tr>
</thead>
<tbody data-bind="foreach: customers" >
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Age"></td>
<td data-bind="text: Comments"></td>
</tr>
</tbody>
</table>
<br />
<input type="button" id="btnGetCustomers" value="Get Customers" data-bind="click: getCustomers" />