我已经重构了你的 jsFiddle。希望您现在可以更好地理解 knockoutJS。这不是您的整个页面/淘汰赛,但我认为使用此代码段可以解决您的问题。
标记:
<button id="searchEmployees" type="button" data-bind="click: search">Search</button>
<li data-bind="foreach: Employees">
ID: <span data-bind="text: Id"></span><br/>
Name: <span data-bind="text: Name"></span><br/>
Active: <span data-bind="click: ToggleActivation, text: IsActive"></span> <-- click<br/>
</li>
<span data-bind="text: Employees().length"></span> of
<span data-bind="text: AllEmployees().length"></span>
js/视图模型
function Employee(id, name, isactive){
var self = this;
self.IsActive = ko.observable(isactive);
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.ToggleActivation = function () {
if(self.IsActive() === true)
self.IsActive(false);
else
self.IsActive(true);
};
}
var searchEmployeeViewModel = function () {
var self = this;
self.Employees = ko.observableArray([]);
self.AllEmployees = ko.observableArray([]);
self.search = function () {
//Ajax call to populate Employees - foreach on onsuccess
var employee1 = new Employee(2, "Jane Doe", true);
var employee2 = new Employee(3, "Kyle Doe", false);
var employee3 = new Employee(4, "Tyra Doe", false);
var employee = new Employee(1, "John Doe", true);
self.AllEmployees.push(employee);
self.AllEmployees.push(employee1);
self.AllEmployees.push(employee2);
self.AllEmployees.push(employee3);
self.Employees.push(employee);
}
}
$(document).ready(function () {
ko.applyBindings(new searchEmployeeViewModel());
});
或者如果你不喜欢在这里阅读我的代码,你可以简单地使用 我的 jsFiddle ;)