我在表格中有一个列,其中包含x-editable绑定值。页面加载后,作为ko绑定的结果,为每一行调用成功处理程序(这很好,我可以避免这种情况)。但是一旦页面设置完毕,我就继续更改一个值(将行的employeeId设置为7位数),不再调用成功处理程序。通过打开的控制台日志看到这个小提琴:
http://jsfiddle.net/csabatoth/y3rfe6Lw/6/
HTML:
<table style="table table-striped">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Employee ID</td>
</tr>
</thead>
<tbody data-bind="foreach: candidates">
<tr>
<td><span data-bind="text: firstName"></span></td>
<td><span data-bind="text: lastName"></span></td>
<td><span data-bind="editable: employeeId, editableOptions: { validate: $root.validateEmployeeId, success: $root.persistEmployeeId($data) }"></span></td>
</tr>
</tbody>
</table>
JS:
$(document).ready(function () {
function AppViewModel() {
var self = this;
self.validateEmployeeId = function (value) {
if (value == null || !value.match(/^\d{7}$/))
return 'Invalid EmployeeID';
}
self.persistEmployeeId = function (data) {
console.log(data.employeeId);
}
self.candidates = ko.observableArray([
{ firstName: "John", lastName: "Dow", employeeId: 1001, applicantId: 1 },
{ firstName: "Jane", lastName: "Doe", employeeId: 1002, applicantId: 2 },
{ firstName: "Foo", lastName: "Bar", employeeId: 1003, applicantId: 3 }
]);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
我需要坚持数据更改。我尝试通过使employeeId ko.observable并订阅它的change事件来解决这个问题。但是对于订阅,我只接收newValue作为参数。我需要数据行,以及来自它的applicantId。 employeeId可能不是唯一的,我需要持久性API调用需要applicantId和employeeId。
我该如何解决这个问题?
答案 0 :(得分:1)
我无法用success
绑定做你想做的事情(我不认为你可以做到)但我只是使用了Knockout subscribe
声明Applicant
ViewModel,因为我们需要employeeId成为可订阅的观察者:
var Applicant = function (model) {
var self = this;
self.firstName = model.firstName;
self.lastName = model.lastName;
self.employeeId = ko.observable(model.employeeId);
self.applicantId = model.applicantId;
self.employeeId.subscribe(function (newValue) {
console.debug('Applicant ' + self.applicantId + ' now has employeeId: ' + newValue);
});
}
更改候选arrray人口以改为使用申请人ViewModel:
var candidates = [
new Applicant({ firstName: "John", lastName: "Dow", employeeId: 1001, applicantId: 1 }),
new Applicant({ firstName: "Jane", lastName: "Doe", employeeId: 1002, applicantId: 2 }),
new Applicant({ firstName: "Foo", lastName: "Bar", employeeId: 1003, applicantId: 3 })
];
self.candidates = ko.observableArray(candidates);