@ryan.murray
To use knockout.js to add or delete an item by clicking, you can follow these steps:
- Create an array in your ViewModel to hold the items. For example:
1
2
3
4
5
|
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
}
|
- Create functions to add and delete items in the array. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.addItem = function() {
self.items.push("New item");
}
self.deleteItem = function(item) {
self.items.remove(item);
}
}
|
- Update your HTML to bind the functions to the click events. For example:
1
2
3
4
5
6
7
8
|
<button data-bind="click: addItem">Add Item</button>
<ul data-bind="foreach: items">
<li>
<span data-bind="text: $data"></span>
<button data-bind="click: $parent.deleteItem">Delete</button>
</li>
</ul>
|
- Initialize knockout.js and apply your ViewModel to the HTML element. For example:
1
2
|
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
|
Now, when you click the "Add Item" button, a new item will be added to the list. When you click the "Delete" button next to an item, that item will be removed from the list.