I am trying to create a simple ToDo list by loosely following the interactive tutorial on the Knockout site.
I can add an item to a list, but I can’t remove it. What am I doing wrong ??
function ToDo(stuff) {
this.toDoItem = stuff;
}
function ToDoViewModel() {
this.toDoItems = ko.observableArray([
new ToDo("Watch Person of Interest"),
new ToDo("Study for Midterm exam"),
new ToDo("Buy groceries for Luis")
]);
this.addToDoItem = function() {
this.toDoItems.push(new ToDo($('.txt').val()));
$('.txt').val('');
}
this.removeToDoItem = function(item) {
this.toDoItems.remove(item);
}
}
ko.applyBindings(new ToDoViewModel());
Here is the markup inside a ‘body’ tag:
<table>
<tr>
<td>ToDo List</td>
</tr>
<tbody data-bind="foreach: toDoItems">
<tr>
<td><label data-bind="text: toDoItem"></label></td>
<td><a href="#" data-bind="click: $root.removeToDoItem">Remove</a></td>
</tr>
</tbody>
</table>
<input class="txt"/>
<button data-bind="click: addToDoItem">Add Item</button>
Scope is your problem. The error you should be seeing is:
(Or something similar) Which essentially means that
thisisn’t within theToDoViewModelscope but within the click event scope sothisis a different object reference (and therefor doesn’t have aremoveToDoItemmethod).However if you store the reference (like many examples using
var self = this) you can then referenceself.toDoItemslater and the list will be located. Basically:You can probably change all reference of
this.toself.(as long as it’s referencing objects within the ViewModel’s direct scope).Updated example can be found here.