我正在制作一个简单的列表应用程序来学习 KnockoutJS。现在我可以添加一个任务,当我单击“删除”链接时,该任务将从视图中删除。我在底部有一些使用 ko.computed 函数的任务。当我添加任务时它会更新,但是当我删除任务时,数字保持不变。有谁知道下面的代码有什么问题?
这是我的 JS:
$(function() {
var Todo = function (task, complete) {
this.task = task;
this.complete = complete;
}
var AppViewModel = function(todos) {
var self = this;
//Create an observable array of Todo objects
self.toDoItems = ko.observableArray([
{ task: "Learn KnockoutJS", complete: false}
]);
//Add a new todo
self.add = function() {
self.toDoItems.push(new Todo($('.txt').val()));
$('.txt').val('');
};
//Remove a todo
self.remove = function(item) {
self.toDoItems.destroy(item);
}
//Mark a todo complete
self.complete = function (item) {
item.complete = true;
}
//Count active tasks
self.remainingTasks = ko.computed(function() {
return self.toDoItems().length;
})
}
ko.applyBindings(new AppViewModel());
});
这是我的观点:
<h3>Tasks</h3>
<table>
<tbody data-bind="foreach: toDoItems">
<tr>
<td><input type="checkbox" data-bind="click: $root.complete"></td>
<td class="todo-item"><label data-bind="text: task"></label></td>
<td class="remove"><a href="#" data-bind="click: $root.remove">Remove</a></td>
</tr>
</tbody>
</table>
<br>
<input class="txt" />
<button data-bind="click: add">Add</button><br><br>
There are <strong data-bind="text: remainingTasks"></strong> tasks here.<br>